基于内容提取列CSV python

2024-10-01 00:29:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv文件如下

h1,h2,h3
1 year,homo sapiens,fibrous tissue
3 minutes,homo sapiens,fibrous tissue
2 hours,homo sapiens,epithelial tissue

我只想得到包含我提供的字符串的列。例如,如果我说year,则需要将整个列追加到一个列表中,比如[1year,3minutes,2hours]。我完全不知道该怎么办。我真的很感谢你的帮助。在

编辑:问题是,数据可以在任何列中。在


Tags: 文件csv字符串列表h2h1yearh3
2条回答

我们可以使用列表理解和anystr.contains的组合:

In [183]:
# filter the columns for only those that contain our text of interest
cols_of_interest = [col for col in df if any(df[col].str.contains('year'))]
cols_of_interest
Out[183]:
['h1']
In [184]:
# use the list as a column filter
df[cols_of_interest]
Out[184]:
          h1
0     1 year
1  3 minutes
2    2 hours

因此,通过调用向量化的str方法^{}来测试列中的any值是否包含感兴趣的文本。在

很容易将列表理解打包到返回列表的函数中:

^{pr2}$

试试这个

f=open('your_file.csv','r')

x=[]
for i in f:
    x.append(i)


"first column"

for i in range(len(x)):
    print x[i].split(',')[0]

输出 h1

1年

3分钟

2小时

^{pr2}$

输出:

氢气

智人

智人

智人

相关问题 更多 >