Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用循环Python处理数据帧的列_Python_Dataframe_Concatenation - Fatal编程技术网

使用循环Python处理数据帧的列

使用循环Python处理数据帧的列,python,dataframe,concatenation,Python,Dataframe,Concatenation,我想使用循环来连接数据帧中几列的值 您可以找到实际的数据帧: Artist_1 Artist_2 Artist_3 Lady Antebellum ? ? Reba McEntire ? ? Wanda Jackson ? ? Carrie Underwood ? ? ?

我想使用循环来连接数据帧中几列的值

您可以找到实际的数据帧:

 Artist_1                Artist_2   Artist_3
Lady Antebellum              ?         ?
Reba McEntire                ?         ?
Wanda Jackson                ?         ?
Carrie Underwood             ?         ?
       ?                     ?         ?
The Bellamy Brothers         ?         ?
Keith Urban          Miranda Lambert   ?
Sam Hunt                     ?         ?
Johnny Cash                  ?         ?
Johnny Cash            June Carter     ?
Highwaymen                   ?         ?
Loretta Lynn                 ?         ?
Sissy Spacek                 ?         ?
Loretta Lynn         Sheryl Crow    Miranda Lambert
Charley Pride                ?         ?
预期的结果是:

Artist
Lady Antebellum
Reba McEntire
Wanda Jackson
Carrie Underwood
?
The Bellamy Brothers
Keith Urban, Miranda Lambert
Sam Hunt
Johnny Cash
Johnny Cash, June Carter
Highwaymen
Loretta Lynn
Sissy Spacek
Loretta Lynn,  Sheryl Crow, Miranda Lambert
Charley Pride

这是一种使用
pd.DataFrame.apply
/
str.join
后跟
pd.Series.replace
来说明不存在名称的实例的方法:

import pandas as pd

df = pd.DataFrame({'Artist_1': ['A', 'B', '?', 'D', '?', 'E'],
                   'Artist_2': ['?', '?', '?', 'G', '?', 'I'],
                   'Artist_3': ['J', '?', '?', '?', 'M', 'N']})

df['Artist_All'] = df.apply(lambda x: ', '.join([i for i in x if i != '?']), axis=1)\
                     .replace('', '?')

print(df)

  Artist_1 Artist_2 Artist_3 Artist_All
0        A        ?        J       A, J
1        B        ?        ?          B
2        ?        ?        ?          ?
3        D        G        ?       D, G
4        ?        ?        M          M
5        E        I        N    E, I, N

或者,您可以使用列表:

df['Artist_All'] = [', '.join([i for i in x if i != '?']) for x in df.values]
df['Artist_All'] = df['Artist_All'].replace('', '?')

你好谢谢你的反馈。嗨。感谢您的反馈,但我有以下错误:“序列项1:预期的str实例,找到的float”,“发生在索引0”