将多个列值合并到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=1
到apply
,然后将dtype转换为str
和join
:>
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.