我有一个 DataFrame 将特定文本存储在多个列中。我正在尝试过滤掉具有此值的 DataFrame 中的所有行。
id,col1,col2,col3,col4
1001,apple,banana,pear,kiwi
1002,,apple,,
1003,banana,kiwi,,
1004,pear,orange,apple,
鉴于上面的示例,我试图过滤所有包含单词 apple 的行以及该行的 ID。
for col in df:
apple = df[df[col].astype(str).str.contains("apple")]
但这会返回空行。
预期输出:
id,value
1001,apple
1002,apple
1004,apple
请您参考如下方法:
想法被设置为 id 以索引并将非 apple 值替换为 DataFrame.where 缺失的值,所以在 DataFrame.stack 之后使用 MultiIndex 获取 Series,因此添加双 Series.reset_index - 第一个用于删除第一级,第二个用于将 Series 转换为 2 列 DataFrame:
df = (df.set_index('id')
.where(lambda x: x == 'apple')
.stack()
.reset_index(level=1, drop=True)
.reset_index(name='val')
)
print (df)
id val
0 1001 apple
1 1002 apple
2 1004 apple
对于测试子字符串,使用 Series.str.contains并通过 DataFrame.dropna 删除缺失的行:
df = (df.set_index('id')
.stack()
.where(lambda x: x.str.contains('apple'))
.dropna()
.reset_index(level=1, drop=True)
.reset_index(name='val')
)
print (df)
id val
0 1001 apple
1 1002 apple
2 1004 apple
