繁体   English   中英

合并具有多个值的列 pandas dataframe

[英]Merge columns with more than one value in pandas dataframe

我使用 pandas 在 Python 中得到了这个 DataFrame:

第 1 列 第 2 栏 第 3 栏
你好 a,b,c 1,2,3
你好 b,c,a 4,5,6

第 3 列中的值属于第 2 列中的类别。有没有办法将第 2 列和第 3 列组合起来,我得到这个 output?

第 1 列 一种 b c
你好 1个 2个 3个
你好 6个 4个 5个

任何建议都会非常有帮助! 谢谢!

您可以在exploding逗号后使用pd.crosstab

new_df = ( df.assign(t=df['Column 2'].str.split(','), a=df['Column 3'].str.split(',')).
                      explode(['t', 'a']) )

output = ( pd.crosstab(index=new_df['Column 1'], columns=new_df['t'], 
                     values=new_df['a'], aggfunc='sum').reset_index() ) 

Output:

t   Column 1    a   b   c
0   hello       1   2   3
1   hi          4   5   6
df.apply(lambda x: pd.Series(x['Column 3'].split(','), index=x['Column2'].split(',')), axis=1)    

output:

    a   b   c
0   1   2   3
1   4   5   6

结果使df1concat

df1 = df.apply(lambda x: pd.Series(x['Column 3'].split(','), index=x['Column2'].split(',')), axis=1)

pd.concat([df['Column 1'], df1], axis=1)

output:

    col1    a   b   c
0   hello   1   2   3
1   hi      4   5   6

效率方面,我会说在香草 python 中进行所有争论并创建一个新的 dataframe:

from collections import defaultdict
outcome = defaultdict(list)
for column, row in zip(df['Column 2'], df['Column 3']):
    column = column.split(',')
    row = row.split(',')
    for first, last in zip(column, row):
        outcome[first].append(last)
pd.DataFrame(outcome).assign(Column = df['Column 1'])
   a  b  c Column
0  1  2  3  hello
1  6  4  5     hi

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM