如何在包含全名的列表中提取名称(名字)的第一部分,并放弃包含一部分的名称

2024-09-28 05:23:56 发布

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

我有一个CSV文件,其中包含一列名称。我想要的是一个python代码来检查列中的每个名称,并查看名称是否包含多个部分,它只包含第一个部分并将其附加到新的CSV文件列表中,同时跳过旧CSV文件中仅包含一个部分的任何名称

比如说

输入CSV文件

Column1
Metarhizium robertsii ARSEF 23
Danio rerio
Parascaris equorum
Hevea
Gossypium
Vitis vinifera

输出CSV文件应为

Column1
Metarhizium
Danio
Parascaris
Vitis

Tags: 文件csv代码名称列表column1daniorerio
3条回答

名称是否总是用空格分隔

您可以在python中使用re模块并使用正则表达式,或者如果您想要简单的东西,也可以在python中使用str.split()方法:

for name in column:
    split_name = name.split(' ', 1) #Splits the name once after the first space and returns a list of strings
    if len(split_name) > 1: new_csv.write(split_name[0]) #write the first part of the split up name into the new csv
   

您可以拆分,然后应用函数len来屏蔽结果,然后获取行中筛选的第一个元素

import pandas as pd
df = pd.read_csv("input.csv")
splitted = df.Column1.apply(lambda x: x.split())
output = splitted[splitted.apply(len) > 1].apply(lambda x: x[0])
output.to_csv("output.csv")
# > ,Column1
#  0,Metarhizium
#  1,Danio
#  2,Parascaris
#  5,Vitis

您可以首先为具有多个单词的值创建一个标志,然后使用apply()方法并编写lambda函数来检索所有名称中的第一个单词

flag = df.loc[:,'Column1'].str.split(' ').apply(len) > 1
split_names = lambda name: name.split()[0] if (len(name.split())) else None
new_df = df.loc[flag,'Column1'].apply(split_names)
new_df.to_csv('output.csv', index=False)

相关问题 更多 >

    热门问题