如果字符串以熊猫中的某些字符开头,则选择行

时间:2020-01-27 07:28:52

标签: python string pandas

我有一个csv文件作为下面的图片

enter image description here

我正在尝试查找以字母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)) )

2 个答案:

答案 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