将多个列值合并到python pandas的一列中 [英] Merge multiple column values into one column in python pandas

查看:168
本文介绍了将多个列值合并到python pandas的一列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的熊猫数据框:

I have a pandas data frame like this:

   Column1  Column2  Column3  Column4  Column5
 0    a        1        2        3        4
 1    a        3        4        5
 2    b        6        7        8
 3    c        7        7        

我现在要做的是获取一个包含Column1和新columnA的新数据框.像这样:columnA应该包含第2列-(to)n的所有值(其中n是从Column2到行末的列数):

What I want to do now is getting a new dataframe containing Column1 and a new columnA. This columnA should contain all values from columns 2 -(to) n (where n is the number of columns from Column2 to the end of the row) like this:

  Column1  ColumnA
0   a      1,2,3,4
1   a      3,4,5
2   b      6,7,8
3   c      7,7

我如何最好地解决这个问题?任何意见将是有益的.预先感谢!

How could I best approach this issue? Any advice would be helpful. Thanks in advance!

推荐答案

您可以逐行调用apply传递axis=1apply,然后将dtype转换为strjoin:

You can call apply pass axis=1 to apply row-wise, then convert the dtype to str and join:

In [153]:
df['ColumnA'] = df[df.columns[1:]].apply(
    lambda x: ','.join(x.dropna().astype(str)),
    axis=1
)
df

Out[153]:
  Column1  Column2  Column3  Column4  Column5  ColumnA
0       a        1        2        3        4  1,2,3,4
1       a        3        4        5      NaN    3,4,5
2       b        6        7        8      NaN    6,7,8
3       c        7        7      NaN      NaN      7,7

在这里,我打电话给dropna以摆脱NaN,但是我们需要再次强制转换为int,因此我们不会以浮点数作为str结束.

Here I call dropna to get rid of the NaN, however we need to cast again to int so we don't end up with floats as str.

这篇关于将多个列值合并到python pandas的一列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆