有没有办法根据列名拆分 pandas 数据框?例如,考虑数据框具有以下列 df = ['A_x', 'B_x', 'C_x', 'A_y', 'B_y', 'C_y']
我想创建两个数据帧 X = ['A_x', 'B_x', 'C_x']
和 Y = ['A_y', 'B_y', 'C_y']
.
我知道有可能这样做:
d = {'A': df.A_x, 'B': df.B_x, 'C': df.B_x}
X = pd.DataFrame (data=d)
但这并不理想,因为在我的例子中,我在 df
中有 2200 列。有没有更优雅的解决方案?
最佳答案
你可以使用 df.filter(regex=...)
:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(2, 10),
columns='Time A_x A_y A_z B_x B_y B_z C_x C_y C-Z'.split())
X = df.filter(regex='_x')
Y = df.filter(regex='_y')
产量
In [15]: X
Out[15]:
A_x B_x C_x
0 -0.706589 1.031368 -0.950931
1 0.727826 0.879408 -0.049865
In [16]: Y
Out[16]:
A_y B_y C_y
0 -0.663647 0.635540 -0.532605
1 0.326718 0.189333 -0.803648
关于python - 根据列名拆分 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32739895/