【问题标题】:Removing a value in a specific row of a column without removing the entire row in a pandas dataframe [duplicate]删除列的特定行中的值而不删除熊猫数据框中的整行[重复]
【发布时间】:2021-04-01 18:01:54
【问题描述】:

如果我有一个像这样的 csv,第一个 A、B、C 是列标题:

A, B, C

A1,A2,A3
blah,B2,B3
C1,C2,C3
blahxxxxxtr,D4,D5

如何删除包含“blah”的条目或其中包含“blah”的任何内容,而不删除整行。

这是目前为止的工作:

import pandas as pd
file = r"\\fileserver\data\test.csv"
df = pd.read_csv(file)
for index, row in df.iterrows():
   if 'blah' in str[row[0]:
        print(row['A']
        #this is where I don't know how to remove 'blah' if this is True
        #I want the new value of that to be a blank field, so  '',B2,B3
        #Same would go for the 4th row, '',D4,D5 
        # Using a drop command removes the whole row. 
df.to_csv(file, index = false)    

这成功打印了第 2 行和第 4 行 'blah' 值。
如何删除并用空白字符串替换 'blah',所以它没有任何内容,甚至在该特定行的该列中也没有 Nan?

【问题讨论】:

  • 试试df.replace('blah', '')。

标签: python pandas dataframe


【解决方案1】:

你可以简单地使用替换。

df.replace(to_replace='blah', value='the value you want', inplace=True)

或者如果您想替换某个列值,请使用

df[colname].replace(to_replace='blah', value='the value you want', inplace=True)

如果 inplace 设置为 true,则 df 将在内部更新。否则将返回一个值改变的df

【讨论】:

  • 苛刻,如果其中一行看起来像:blahfffff,B,C - 如果它“包含”blah,我如何要求替换?
  • @MikeColeman df.loc[df[colname].str.contains('blah'), colname] = '',其中colname 是您作为字符串的列名。
猜你喜欢
  • 1970-01-01
  • 2019-11-12
  • 2017-09-27
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 2015-04-14
  • 2021-12-02
  • 1970-01-01
相关资源
最近更新 更多