【问题标题】:Combine two pandas columns as index, create new column with their column names as values将两个 pandas 列合并为索引,以列名作为值创建新列
【发布时间】:2020-12-23 16:40:30
【问题描述】:

我有一个 df:

import pandas as pd
df = pd.DataFrame({"A": [1, 3, 7, 10], "B": [2, 5, 8, 11], "C": list("WXYZ") })  
print(df)

>>>    A   B  C
>>>0   1   2  W
>>>1   3   5  X
>>>2   7   8  Y
>>>3  10  11  Z

我现在想将AB 这两列合并为索引,保留C,并创建一个新列vals 代表之前的AB 列:

     vals  C
         
1       A  W
2       B  W
3       A  X
5       B  X
7       A  Y
8       B  Y
10      A  Z
11      B  Z

我用stackpivotmelt 尝试了几个版本,但都没有成功。我可以跛行通过终点线:

import numpy as np
n = len(df.A)
arr = np.zeros((2, 2*n))
arr[0, :n] = df.A
arr[0, n:] = df.B
arr[1, :n] = 0
arr[1, n:] = 1

new_df = pd.DataFrame(arr.T, columns=["ind", "vals"], dtype="int").set_index("ind")
new_df["C"] = np.tile(df.C, 2)
new_df.sort_index(inplace=True)
print(new_df)

>>>     vals  C
>>>ind         
>>>1       0  W
>>>2       1  W
>>>3       0  X
>>>5       1  X
>>>7       0  Y
>>>8       1  Y
>>>10      0  Z
>>>11      1  Z

这不仅看起来很糟糕,而且有几个缺点(dtype 变化等)。我敢打赌,对于这个问题有更好的 pandas 解决方案。

【问题讨论】:

    标签: python pandas dataframe reshape


    【解决方案1】:

    确实是melt

    df.melt('C').set_index('value')
    

    输出:

           C variable
    value            
    1      W        A
    3      X        A
    7      Y        A
    10     Z        A
    2      W        B
    5      X        B
    8      Y        B
    11     Z        B
    

    【讨论】:

    • 我喜欢我现在看起来很荒谬,因为我尝试使用除 C 之外的所有列进行融合。当然就是这样。而且我只是尝试了不止一列C,没问题。太好了。
    猜你喜欢
    • 2015-02-09
    • 2021-05-30
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多