我正在尝试在 pandas
中执行以下操作。对 pandas
这样做有什么建议吗?
In [1]: input = pd.DataFrame({"X_1": [1], "X_2": [2], "X_3": [5], "Y_1": [1.2], "Y_2": [2.3], "Y_3": [3.4]})
In [2]: input
Out[2]:
X_1 X_2 X_3 Y_1 Y_2 Y_3
0 1 2 5 1.2 2.3 3.4
In [3]: output = pd.DataFrame({"X": [1,2,5], "Y": [1.2, 2.3, 3.4]})
In [4]: output
Out[4]:
X Y
0 1 1.2
1 2 2.3
2 5 3.4
最佳答案
使用str.split
和stack
。
df.columns = df.columns.str.split('_', expand=True)
df.stack().loc[0]
X Y
1 1 1.2
2 2 2.3
3 5 3.4
注意:索引是 [1, 2, 3]
匹配原始列。
关于python - Pandas 中的列到行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37840821/