[英]Split string from a preset list of strings from pandas df column
我有一个熊猫数据框,如下所示。 它有大约一百万行。
name = ['Jake','Matt', 'Henry']
0 A
1 Jake Hill
2 Matt Dawn
3 Matt King
4 White Henry
5 Hyde Jake
我想迭代列表和df ['A']列并仅返回名字。 例如,最终的数据框应如下所示。
0 A
1 Jake
2 Matt
3 Matt
4 Henry
5 Jake
提前致谢。 我是python的新手,所以仍然找出最简单的方法。
您有一个要匹配的名称列表,以及要检查的一系列名称。 在这里使用带str.extract
的正则表达式。
df.A.str.extract(r'({})'.format('|'.join(name)))
0
0 Jake
1 Matt
2 Matt
3 Henry
4 Jake
这是实现此目的的一种方法:
first_name = ['Jake','Matt', 'Henry']
df = pd.DataFrame({'A': ['Jake Hill', 'Matt Dawn', 'Matt King', 'Henry White', 'Jake Hyde']})
df['B'] = df['A'].str.split().apply(lambda x: x[0] if x[0] in first_name else ' '.join(x))
你得到:
A B
0 Jake Hill Jake
1 Matt Dawn Matt
2 Matt King Matt
3 Henry White Henry
4 Jake Hyde Jake
你需要:
first_name = ['Jake','Matt', 'Henry']
df = pd.DataFrame({'A': ['Jake Hill', 'Matt Dawn', 'Matt King', 'Henry White','Jake Hyde','Dwayne John']})
def func(x):
for k in first_name:
if k in x:
return k
return x
df['A'] = df['A'].apply(lambda x: func(x))
输出:
A
0 Jake
1 Matt
2 Matt
3 Henry
4 Jake
5 Dwayne John
name = ['Jake','Matt', 'Henry']
df = pd.read_csv("file.csv")
#filling nan values in-case if it is there
df.fillna(0, inplace = True)
df["First Name"] = df.A.apply(lambda x: list(set(x.split(" ")) & set(name))[0] if x != 0 else "Not Found")
输出:
A First Name
0 Jake Hill Jake
1 Matt Dawn Matt
2 Matt King Matt
3 Henry White Henry
4 Hyde Jake Jake
除了早期的编辑,我现在理解你想要替换,这可以用列表理解完成,如下所示,拆分列A
Fist并选择它的第一个索引并使用apply
方法传递给lambda。
DataFrame结构:
df
A
0 Jake Hill
1 Matt Dawn
2 Matt King
3 Henry White
4 Jake Hyde
你的name
Var ..
$ name
['Jake', 'Matt', 'Henry']
您最终需要的数据集:
参数n可用于限制输出中的分割数。
df['A'] = df['A'].str.split(n=1, expand=True)[0].apply(lambda x: x if x in name else ' '.join(x))
print(df)
A
0 Jake
1 Matt
2 Matt
3 Henry
4 Jake
如果您没有按下从Var获取名称并且最终目标是从数据帧中获取名字,那么应该很简单:
>>> df
A
0 Jake Hill
1 Matt Dawn
2 Matt King
3 Henry White
4 Jake Hyde
>>> df['A'].str.split(n=1, expand=True)[0]
0 Jake
1 Matt
2 Matt
3 Henry
4 Jake
Name: 0, dtype: object
或者如果您想要替换A
列A
原位..
df['A'] = df['A'].str.split(n=1, expand=True)[0]
尝试使用:
A_final=A[0].str.split(' ',expand=True, n=1).str.get(0) A_final[0]
,你的问题解决了。
此方法不会被包含其中一个名字字符串的姓氏所欺骗,例如“Matten”或“Jakes”,如果它们都在名字列表中找到,则将组合使用名字和姓氏,例如“马特亨利”(在输出数据框中显示“MattHenry”)。
# split the name strings into columns as new dataframe
df1 = df.A.str.split(' ', expand=True)
# Keep the first names in the new dataframe and fill the rest with
# empty strings, then sum the df1 column string values to make a new array
names_result = np.where(df1.isin(name), df1, '').sum(axis=1)
# find the array indexes where no first names were found
no_match_idx = np.where(names_result == '')[0]
# fill the no first name index locations with original dataframe values
names_result[no_match_idx] = df.A.values[no_match_idx]
# make a dataframe using the results
df_out = pd.DataFrame(names_result, columns=['A'])
# to find names with a first and last name that are both found in the
# first names list:
# df_out['dups'] = df1.isin(name).sum(axis=1) > 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.