【问题标题】:Combine values of two columns of dataframe into one column将两列数据框的值合并为一列
【发布时间】:2019-12-19 23:02:28
【问题描述】:

嗨,我想将两个列值附加到一个列中,如下面的 pandas 所示。 谁能帮我做这件事?

| t1   | t2   | v1 | v2 |
|------|------|----|----|
| 0.0  | 10   | 1  | -1 |
| 0.42 | 0.78 | 1  | -1 |

新数据框

| t1,t2 combined | v1,v2 combined |
|----------------|----------------|
| 0.0            | 1              |
| 0.42           | 1              |
| 10             | -1             |
| 0.78           | -1             |

【问题讨论】:

标签: python pandas


【解决方案1】:

pd.wide_to_long 应该可以工作:

df['value'] = list(range(0,2))
pd.wide_to_long(df, stubnames=['t', 'v'], i='value', j='dropme', sep='').reset_index().drop(columns=['value', 'dropme'])                                                           

       t  v
0   0.00  1
1   0.42  1
2  10.00 -1
3   0.78 -1

【讨论】:

    【解决方案2】:

    如果您正在寻找一个班轮,那么

    df[['t1', 'v1']].append(df[['t2', 'v2']].rename(columns={'t2': 't1', 'v2': 'v1'}), ignore_index=True)
    

    【讨论】:

      【解决方案3】:

      我认为您要查找的词是 concatenate。

      data = [ 
          [0.0, 10, 1, -1], 
          [0.42, 0.78, 1, -1]
      ]
      df = pd.DataFrame(data, columns=['t1', 't2', 'v1', 'v2'])
      v1 = df.set_index('t1')['v1'].rename('v')
      v1.index.name = 't'
      v2 = df.set_index('t2')['v2'].rename('v')
      v2.index.name = 't'
      combined = pd.concat([v1, v2])
      print(combined)
      

      输出:

      t
      0.00     1
      0.42     1
      10.00   -1
      0.78    -1
      Name: v, dtype: int64
      

      事实证明,在串联系列时,您不需要匹配索引和列名。因此,这在有 n 组一致命名的列的设置中实现了结果:

      combined = pd.concat([df.set_index(f"t{i}")[f"v{i}"] for i in range(1, 3)])
      print(combined)
      

      输出:

      0.00     1
      0.42     1
      10.00   -1
      0.78    -1
      dtype: int64
      

      唯一的区别是生成的系列是未命名的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-21
        • 2021-05-17
        • 2018-04-16
        • 1970-01-01
        • 2021-03-06
        • 1970-01-01
        • 2023-01-23
        • 2018-10-08
        相关资源
        最近更新 更多