简体   繁体   English

将两个 pandas 列合并为索引,创建新列,并将其列名作为值

[英]Combine two pandas columns as index, create new column with their column names as values

I have a df:我有一个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

I want to combine now the two columns A and B as the index, keep C , and create a new column vals that represents the former A and B columns:我现在想将AB两列合并为索引,保留C ,并创建一个代表前AB列的新列vals

     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

I tried several versions with stack , pivot , melt without success.我尝试了几个带有stack的版本pivotmelt没有成功。 I could limp through the finishing line with:我可以通过终点线跛行:

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

which not only looks horrible but also has several drawbacks (dtype changes and such).这不仅看起来很可怕,而且有几个缺点(dtype 变化等)。 I bet there is a better pandas solution to this problem.我敢打赌,对于这个问题有更好的 pandas 解决方案。

It's indeed melt :它确实melt

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

Output: Output:

       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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM