我制作了以下代码,从我的df中取出了所有零。但是当有一个包含零的数字时,它也会将它们取出。
e.g.
3016.2 316.2
0.235 .235
data_usage_df['Data Volume (MB)'] = data_usage_df['Data Volume (MB)'].str.replace('0', '')
你能帮我弄清楚我是如何完全匹配等于0的单元格,并用空白值替换它。
答案 0 :(得分:3)
data_usage_df = data_usage_df.astype(str)
data_usage_df['Data Volume (MB)'].replace(['0', '0.0'], '', inplace=True)
答案 1 :(得分:1)
我认为您需要添加^
以匹配字符串的开头,并$
添加字符串的结尾:
data_usage_df['Data Volume (MB)']=data_usage_df['Data Volume (MB)'].str.replace('^0.0$', '')
样品:
data_usage_df = pd.DataFrame({'Data Volume (MB)':[3016.2, 0.235, 1.4001, 0, 4.00]})
print (data_usage_df)
runfile('C:/Dropbox/work-joy/so/_t/test.py', wdir='C:/Dropbox/work-joy/so/_t')
Data Volume (MB)
0 3016.2000
1 0.2350
2 1.4001
3 0.0000
4 4.0000
data_usage_df['Data Volume (MB)'] = data_usage_df['Data Volume (MB)'].astype(str)
data_usage_df['Data Volume (MB)']=data_usage_df['Data Volume (MB)'].str.replace('^0.0$', '')
print (data_usage_df)
Data Volume (MB)
0 3016.2
1 0.235
2 1.4001
3
4 4.0
另一种解决方案是转换列to_numeric
,其中0
给出空格:
data_usage_df['Data Volume (MB)'] = data_usage_df['Data Volume (MB)'].astype(str)
data_usage_df.ix[pd.to_numeric(data_usage_df['Data Volume (MB)'], errors='coerce') == 0,
['Data Volume (MB)']] = ''
print (data_usage_df)
Data Volume (MB)
0 3016.2
1 0.235
2 1.4001
3
4 4.0