python将删除括号和,在df值中
我有一个数据帧,如下所示:python将删除括号和,在df值中,python,pandas,Python,Pandas,我有一个数据帧,如下所示: column1 column2 column3 column4 6,546 543,254,32 (443,326) (32,000) 4,554 432,885 (88,974) 77,332 n.a - 5,332 - ... ... ... ... # this df stretches for over 500
column1 column2 column3 column4
6,546 543,254,32 (443,326) (32,000)
4,554 432,885 (88,974) 77,332
n.a - 5,332 -
... ... ... ...
# this df stretches for over 500 rows, and all columns could potentially have
# values within brackets, 'n.a', '-'
我遇到的问题是,将(,)
中的所有值替换为-443326
,即删除括号和逗号
我知道我可以执行df.replace('n.a',numpy.nan,inplace=True)
,如果值匹配,这将相应地替换值
但是,对于df.replace('(',numpy.nan,inplace=True)
来说,同样的方法不起作用
我已尝试使用循环解决我的问题:
for i in df.columns():
df[i] = df[i].str.replace('(', '-')
df[i] = df[i].str.replace(')', '')
df[i] = df[i].str.replace(',', '')
这似乎有效,但它给了我一个警告信息:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
怎么
如果你只是想解决
(东西)
问题
d = {
'\(([\d,]+)\)': r'-\1',
}
df.replace(d, regex=True)
column1 column2 column3 column4
0 6,546 543,254,32 -443,326 -32,000
1 4,554 432,885 -88,974 77,332
2 n.a - 5,332 -
这里有一个稍微不同的方法:
In [89]: df.replace(r'[^\d\.]+', '', regex=True).apply(pd.to_numeric, errors='coerce')
Out[89]:
column1 column2 column3 column4
0 6546.0 54325432.0 443326 32000.0
1 4554.0 432885.0 88974 77332.0
2 NaN NaN 5332 NaN
链式替换
df['column_name'] = (df.loc[:, 'column_name'].replace('[)]', '', regex=True)
.replace('[(]', '-', regex=True).astype(float))
@jezrael我想
str
是df[I].str.replace(“\(”,“-”)
@tarashypka-这取决于需要还是Hi@jezrael,我想我一定错过了我上一篇文章中的答案。很抱歉重复了同样的问题。我已经尝试了你提供的解决方案,效果很好!:)
df['column_name'] = (df.loc[:, 'column_name'].replace('[)]', '', regex=True)
.replace('[(]', '-', regex=True).astype(float))