加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如果单元格包含’ – ‘,pandas会更新数据帧值

发布时间:2020-12-20 11:53:25 所属栏目:Python 来源:网络整理
导读:我有一个pandas Dataframe,有46列,6行. Index Column1 Column2 Column3 Column4 ... # Cant type all 46 columns.2012 5626 fooo - barrr2013 5655h booo - barr2014 5626d zooo - -LTM 56 gooo greed - 有没有办法让我通过这个数据帧并更新所有 – 值为0或
我有一个pandas Dataframe,有46列,6行.

Index    Column1    Column2    Column3   Column4      ... # Cant type all 46 columns.
2012     5626       fooo       -         barrr
2013     5655h      booo       -         barr
2014     5626d      zooo       -         -
LTM      56         gooo       greed     -

有没有办法让我通过这个数据帧并更新所有 – 值为0或空值?

我试过了:

for zzz in df.columns:  # since df.columns will return me the names of the columns
    if df_final[zzz].any() == '-':
        df_final[zzz] = 0
        print(df_final)

但是,这只是将所有内容打印出来.它没有转换成0 / null

解决方法

使用 replace将该特定值替换为另一个:

In [71]:
df.replace('-',inplace=True)
df

Out[71]:
  Index Column1 Column2 Column3 Column4
0  2012    5626    fooo       0   barrr
1  2013   5655h    booo       0    barr
2  2014   5626d    zooo       0       0
3   LTM      56    gooo   greed       0

你的代码即使它能够工作也是错误的语义:

for zzz in df.columns: 
    if df_final[zzz].any() == '-':
        df_final[zzz] = 0
        print(df_final)

这个:df_final [zzz] = 0会更新整个列

如果您的代码是:

for zzz in df.columns: 
    if df_final[zzz].any() == '-':
        df_final[zzz] = df_final[zzz].replace('-',0)
        print(df_final)

那么这只会替换满足条件的行,你也可以这样做:

df.apply(lambda x: x.replace('-',0))

为了更紧凑的方法

编辑如果你想用NaN替换然后传递np.NaN而不是0以上.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读