在 pandas 中将多列合并为一列 [英] merging multiple columns into one columns in pandas

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

问题描述

我有一个名为ref(第一个数据帧)的数据帧,其列为c1,c2,c3和c4。

I have a dataframe called ref(first dataframe) with columns c1, c2 ,c3 and c4.

ref= pd.DataFrame([[1,3,.3,7],[0,4,.5,4.5],[2,5,.6,3]], columns=['c1','c2','c3','c4'])
print(ref)
   c1  c2   c3   c4
0   1   3  0.3  7.0
1   0   4  0.5  4.5
2   2   5  0.6  3.0

我想创建一个新列,即c5(第二个数据帧),其中包含所有值

I wanted to create a new column i.e, c5 ( second dataframe) that has all the values from columns c1,c2,c3 and c4.

我尝试了concat,合并了列,但是我无法使它工作。

I tried concat, merge columns but i cannot get it work.

请让我知道您是否有解决方案?

Please let me know if you have a solutions?

推荐答案

您可以使用 堆栈 用于从 DataFrame 系列 >,然后 concat 还原为原始

You can use unstack for creating Series from DataFrame and then concat to original:

print (pd.concat([ref, ref.unstack().reset_index(drop=True).rename('c5')], axis=1))
     c1   c2   c3   c4   c5
0   1.0  3.0  0.3  7.0  1.0
1   0.0  4.0  0.5  4.5  0.0
2   2.0  5.0  0.6  3.0  2.0
3   NaN  NaN  NaN  NaN  3.0
4   NaN  NaN  NaN  NaN  4.0
5   NaN  NaN  NaN  NaN  5.0
6   NaN  NaN  NaN  NaN  0.3
7   NaN  NaN  NaN  NaN  0.5
8   NaN  NaN  NaN  NaN  0.6
9   NaN  NaN  NaN  NaN  7.0
10  NaN  NaN  NaN  NaN  4.5
11  NaN  NaN  NaN  NaN  3.0

用于创建 Series 的替代解决方案是 df numpy array ,由 ,然后通过 ravel

Alternative solution for creating Series is convert df to numpy array by values and then reshape by ravel:

    print (pd.concat([ref, pd.Series(ref.values.ravel('F'), name='c5')], axis=1))
         c1   c2   c3   c4   c5
    0   1.0  3.0  0.3  7.0  1.0
    1   0.0  4.0  0.5  4.5  0.0
    2   2.0  5.0  0.6  3.0  2.0
    3   NaN  NaN  NaN  NaN  3.0
    4   NaN  NaN  NaN  NaN  4.0
    5   NaN  NaN  NaN  NaN  5.0
    6   NaN  NaN  NaN  NaN  0.3
    7   NaN  NaN  NaN  NaN  0.5
    8   NaN  NaN  NaN  NaN  0.6
    9   NaN  NaN  NaN  NaN  7.0
    10  NaN  NaN  NaN  NaN  4.5
    11  NaN  NaN  NaN  NaN  3.0

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

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