pandas 替换元素不起作用 [英] Pandas replacing elements not working

查看:57
本文介绍了 pandas 替换元素不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经查询了此问题,大多数问题是针对更复杂的替换问题.但是,就我而言,我有一个非常简单的数据框作为测试假人.

I have looked up this issue and most questions are for more complex replacements. However in my case I have a very simple dataframe as a test dummy.

目的是用nan替换数据帧中任意位置的字符串,但这似乎行不通(即不替换;不存在任何错误).我尝试用另一个字符串替换,但它也不起作用.例如

The aim is to replace a string anywhere in the dataframe with an nan, however this does not seem to work (i.e. does not replace; no errors whatsoever). I've tried replacing with another string and it does not work either. E.g.

d = {'color' : pd.Series(['white', 'blue', 'orange']),
   'second_color': pd.Series(['white', 'black', 'blue']),
   'value' : pd.Series([1., 2., 3.])}
df = pd.DataFrame(d)
df.replace('white', np.nan)

输出仍然是:

      color second_color  value
  0   white        white      1
  1    blue        black      2
  2  orange         blue      3

推荐答案

您需要分配回

df = df.replace('white', np.nan)

或传递参数inplace=True:

In [50]:
d = {'color' : pd.Series(['white', 'blue', 'orange']),
   'second_color': pd.Series(['white', 'black', 'blue']),
   'value' : pd.Series([1., 2., 3.])}
df = pd.DataFrame(d)
df.replace('white', np.nan, inplace=True)
df

Out[50]:
    color second_color  value
0     NaN          NaN    1.0
1    blue        black    2.0
2  orange         blue    3.0

大多数熊猫操作返回一个副本,并且大多数具有参数inplace,通常默认为False

Most pandas ops return a copy and most have param inplace which is usually defaulted to False

这篇关于 pandas 替换元素不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆