【问题标题】:Pandas DataFrame column concatenationPandas DataFrame 列连接
【发布时间】:2013-11-09 14:28:10
【问题描述】:

我有一个带有 100 万行和 5 列的 pandas Dataframe y。

np.shape(y)  
(1037889, 5)

列值都是 0 或 1。看起来像这样:

y.head()  
a, b, c, d, e  
0, 0, 1, 0, 0  
1, 0, 0, 1, 1  
0, 1, 1, 1, 1  
0, 0, 0, 0, 0

我想要一个包含 100 万行和 1 列的数据框。

np.shape(y)  
(1037889, )

其中的列只是连接在一起的 5 列。

New column  
0, 0, 1, 0, 0  
1, 0, 0, 1, 1  
0, 1, 1, 1, 1  
0, 0, 0, 0, 0

我一直在尝试不同的东西,例如mergeconcatdstack 等... 但似乎无法弄清楚这一点。

【问题讨论】:

    标签: python numpy merge pandas concatenation


    【解决方案1】:

    如果您希望新列将所有数据连接到字符串,那么 apply() 函数是一个很好的例子:

    >>> df = pd.DataFrame({'a':[0,1,0,0], 'b':[0,0,1,0], 'c':[1,0,1,0], 'd':[0,1,1,0], 'c':[0,1,1,0]})
    >>> df
       a  b  c  d
    0  0  0  0  0
    1  1  0  1  1
    2  0  1  1  1
    3  0  0  0  0
    >>> df2 = df.apply(lambda row: ','.join(map(str, row)), axis=1)
    >>> df2
    0    0,0,0,0
    1    1,0,1,1
    2    0,1,1,1
    3    0,0,0,0
    

    【讨论】:

      猜你喜欢
      • 2017-08-08
      • 2018-12-26
      • 2012-07-27
      • 1970-01-01
      • 2014-07-26
      • 2017-02-03
      • 2020-01-07
      • 2021-06-20
      • 1970-01-01
      相关资源
      最近更新 更多