用数据框 Python pandas 中的空白替换 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40128388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:14:37  来源:igfitidea点击:

Replace 0 with blank in dataframe Python pandas

pythonpandasreplace

提问by Joe_ft

I made the following code that takes out all of the zero's from my df. However when there is a number containing a zero it takes them out as well.

我制作了以下代码,从我的 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', '')

Could you help me to figure out how I do an exact match of the cell that equals 0 and replace it with a blank value.

你能帮我弄清楚我如何对等于 0 的单元格进行精确匹配并将其替换为空白值。

采纳答案by b2002

data_usage_df = data_usage_df.astype(str)
data_usage_df['Data Volume (MB)'].replace(['0', '0.0'], '', inplace=True)

回答by jezrael

I think you need add ^for matching start of string and $for end of string:

我认为您需要添加^以匹配字符串的开头和字符串$的结尾:

data_usage_df['Data Volume (MB)']=data_usage_df['Data Volume (MB)'].str.replace('^0.0$', '')

Sample:

样本:

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

Another solution is converting column to_numericand where is 0give empty space:

另一种解决方案是转换列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