我有一个csv文件作为下面的图片
我正在尝试查找以字母A和G开头的任何单词或我想要的任何列表
但是我的代码会返回任何错误。我在做什么错? 这是我的代码
if len(sys.argv) == 1:
print("please provide a CSV file to analys")
else:
fileinput = sys.argv[1]
wdata = pd.read_csv(fileinput)
print( list(filter(startswith("a","g"), wdata)) )
答案 0 :(得分:6)
要获取相关行,请提取第一个字母,然后使用isin
:
df
words frequency
0 what 10
1 and 8
2 how 8
3 good 5
4 yes 7
df[df['words'].str[0].isin(['a', 'g'])]
words frequency
1 and 8
3 good 5
如果要特定列,请使用loc
:
df.loc[df['words'].str[0].isin(['a', 'g']), 'words']
1 and
3 good
Name: words, dtype: object
df.loc[df['words'].str[0].isin(['a', 'g']), 'words'].tolist()
# ['and', 'good']
答案 1 :(得分:3)
使用Series.str.startswith
并将列表转换为元组,并使用DataFrame.loc
通过boolean indexing
进行过滤:
wdata = pd.DataFrame({'words':['what','and','how','good','yes']})
L = ['a','g']
s = wdata.loc[wdata['words'].str.startswith(tuple(L)), 'words']
print (s)
1 and
3 good
Name: words, dtype: object