我有一个 *.xlsx 文件,如下 -
A B C
[['Neutral']] ['nan']
[['Neutral']] ['nan']
Bad [['Negative']] ['Bad']
Meh [['Neutral']] ['Meh']
[['Neutral']] ['nan']
我正在尝试删除 B
和 C
列中的所有 [['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
我的代码完美地找到了所有空值,但无法清除 B
和 C
列变量 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 循环,
说明
查找 A 为空白的位置的索引
替换所选索引处的空白
编辑:
要从特定列中删除,
df.loc[mask,['B','C']]=''
关于 python : Removing the contents of a cell based on a specific condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53082639/