python - 如果字符串以熊猫中的某些字符开头,则选择行
问题描述
我有一个 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)) )
解决方案
要获取相关行,请提取第一个字母,然后使用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']
推荐阅读
- javascript - 如何从应用程序外部访问 Angular js 应用程序?
- python - Keras model.summary() 是否有很好的输出?
- javascript - 从 csv 文件创建一个新数组
- python - Python 回购清理
- c++ - c++ 中 gsl 断言与断言的优势?
- powershell - 如何在 PowerShell 6 中打开新选项卡?
- python - loop in web scraper
- android - 如何修复错误:程序类型已存在:导入 jxl.jar 库时的 jxl.CellView
- c++ - qt-thread 是否共享静态全局变量?
- python - Pandas 在写入 CSV 时不会读取它