当前位置: 代码迷 >> python >> 使用列表中的值过滤DataFrame字符串列
  详细解决方案

使用列表中的值过滤DataFrame字符串列

热度:89   发布时间:2023-07-14 08:45:23.0

我试图过滤我的dataframe列,这是一个字符串字段(我们在这里谈论每个记录的段落),并在列表中包含值列表。 这是我当前的代码:

df = pd.read_csv('Test Data.csv')
test = ['a', 'b']
test = pd.Series(test)
test = list(test.index)
df['string_field'].apply(lambda x:' '.join(x for x in str(x).split() if x in test))

但是,我要做的就是从字符串字段中的文本中删除列表中的值。

您似乎正在尝试使用整数列表来过滤字符串列表...

test = ['a', 'b']
test = pd.Series(test)
test = list(test.index)
print test
>> [0, 1]

不确定为什么要以这种方式操作test ,如果仅将其保存为列表( ['a','b'] ),它应该会产生预期的结果:

import pandas as pd

df = pd.read_csv('Test Data.csv')
print df

test = ['a', 'b']

df['string_field'] = df['string_field'].apply(lambda s:' '.join(x for x in s.split() if x in test))
print df

>>
  string_field
0      a b c d
1      a 1 b 2
2        ab ba
  string_field
0          a b
1          a b
2            
  相关解决方案