首页 > 解决方案 > 如果字符串以熊猫中的某些字符开头,则选择行

问题描述

我有一个 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)) )

标签: pythonstringpandas

解决方案


要获取相关行,请提取第一个字母,然后使用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']

推荐阅读