从pandas df列的预设字符串列表中拆分字符串

时间:2018-11-20 05:29:09

标签: python python-3.x pandas python-2.7

我有一个如下所示的pandas数据框。它有大约一百万行。

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的新手,因此仍然想出最简单的方法来执行此操作。

7 个答案:

答案 0 :(得分:3)

您具有要匹配的名称列表以及要检查的一系列名称。在此处str.extract中使用正则表达式。

df.A.str.extract(r'({})'.format('|'.join(name)))

       0
0   Jake
1   Matt
2   Matt
3  Henry
4   Jake

答案 1 :(得分:2)

这里是实现此目的的一种方法:

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

答案 2 :(得分:2)

您需要:

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

除了以前的编辑(据我了解,现在您要替换),可以通过列表理解如下进行:拆分列A的Fist并选择其第一个索引并传递给lambda使用apply方法。

DataFrame结构:

df
             A
0    Jake Hill
1    Matt Dawn
2    Matt King
3  Henry White
4    Jake Hyde

您的name变量。

$ 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 ..

df['A'] = df['A'].str.split(n=1, expand=True)[0]

答案 5 :(得分:0)

尝试使用:

A_final=A[0].str.split(' ',expand=True, n=1).str.get(0) A_final[0] ,您的问题就解决了。

答案 6 :(得分:0)

此方法不会被包含一个名字字符串之一的姓氏所欺骗,例如“ Matten”或“ Jakes”,并且如果在名字列表中都找到了名字和姓氏,则该方法将合并名字和姓氏,例如“ Matt Henry”(在输出数据框中显示“ 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