问题描述
我试图过滤我的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))
但是,我要做的就是从字符串字段中的文本中删除列表中的值。
1楼
您似乎正在尝试使用整数列表来过滤字符串列表...
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