python : Removing the contents of a cell based on a specific condition

标签 python pandas

我有一个 *.xlsx 文件,如下 -

           A                              B                        C
                                   [['Neutral']]                ['nan']
                                   [['Neutral']]                ['nan']
          Bad                      [['Negative']]               ['Bad']
          Meh                      [['Neutral']]                ['Meh']
                                   [['Neutral']]                ['nan']

我正在尝试删除 BC 列中的所有 [['Neutral']] 和 ['nan'] 值> 仅当它们的值为 null 时。

这是我的代码 -

df1 = pd.read_excel(path)

for i, row in df1.iterrows():
    if pd.isnull(row[0]):
        # del row[1]
        # del row[2]
        row[1] = 0
        row[2] = 0

我的代码完美地找到了所有空值,但无法清除 BC 列变量 s。我做错了什么?

预期输出是-

       A                              B                        C


      Bad                      [['Negative']]               ['Bad']
      Meh                      [['Neutral']]                ['Meh']

是的,空格/单元格应该仍然存在。

最佳答案

试试这个,

mask=df['A'].isnull()
df.loc[mask]=''

输出:

     A               B        C
0                              
1                              
2  Bad  [['Negative']]  ['Bad']
3  Meh   [['Neutral']]  ['Meh']
4                              

对于这个问题,你不需要在 pandas 中使用 for 循环,

说明

  1. 查找 A 为空白的位置的索引

  2. 替换所选索引处的空白

编辑:

要从特定列中删除,

df.loc[mask,['B','C']]=''

关于 python : Removing the contents of a cell based on a specific condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53082639/

相关文章:

python - 无法弄清楚为什么函数会有这样的行为?

python - 将 Pandas 数据框转换为字典

python - 使用 Groupby Pandas DataFrame 手动计算 STD

python - 将 "grouped"列中的数据从长格式转换为宽/方形格式 pd.DataFrame

python - GAE 中的 TaskTooLargeError 是什么?

python - 对mock.sentinel对象的操作

python - 依赖项不适用于我的应用程序

python - 如何使用 pandas 的字符串索引将一列拆分为多列?

python - Pandas 使用 numpy 百分位数重采样?

python - 在 astropy.modeling 中绑定(bind)参数