编程语言
首页 > 编程语言> > python-将多索引DataFrame的行合并为逗号分隔的列表

python-将多索引DataFrame的行合并为逗号分隔的列表

作者:互联网

给定一个多索引DataFrame,我想组合重复的索引对并将其值列出为逗号分隔的列表.例如,输入:

df = pd.DataFrame({'Last Name' : ['Deere','Deere','Foo'   ,'Foo'  ,'Man'   ],
                   'First Name': ['John' ,'Jane' ,'Kung'  ,'Kung' ,'Karate'],
                   'Value1':     [ 1     , 2     , 3      , 4     , 5      ],
                   'Value2':     ['Green','Blue' ,'Yellow','Black','Purple']})

df.set_index(['Last Name','First Name'],inplace=True)

提供:

                          Value1    Value2
Last Name   First Name      
Deere       John          1         Green
            Jane          2         Blue
Foo         Kung          3         Yellow
            Kung          4         Black
Man         Karate        5         Purple

我想将其转换为以下DataFrame:

                          Value1    Value2
Last Name   First Name      
Deere       John          1         Green
            Jane          2         Blue
Foo         Kung          3,4       Yellow,Black
Man         Karate        5         Purple

解决方法:

您可以先将astype列的Value1转换为字符串,然后按agg的姓氏和名字级别将groupby转换为字符串:

df['Value1'] = df['Value1'].astype(str)
result = df.groupby(level=['Last Name','First Name'], sort=False).agg( ','.join)
print result
                     Value1        Value2
Last Name First Name                     
Deere     John            1         Green
          Jane            2          Blue
Foo       Kung          3,4  Yellow,Black
Man       Karate          5        Purple

标签:multi-index,pandas,dataframe,python
来源: https://codeday.me/bug/20191118/2031538.html