简体   繁体   English

根据列名拆分pandas数据框

[英]Splitting pandas data frame based on column name

Is there a way to split a pandas data frame based on the column name? 有没有办法根据列名拆分pandas数据框? As an example consider the data frame has the following columns df = ['A_x', 'B_x', 'C_x', 'A_y', 'B_y', 'C_y'] and I want to create two data frames X = ['A_x', 'B_x', 'C_x'] and Y = ['A_y', 'B_y', 'C_y'] . 作为一个例子,考虑数据帧有以下列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']

I know there is a possibility to do this: 我知道有可能这样做:

d = {'A': df.A_x, 'B': df.B_x, 'C': df.B_x}
X = pd.DataFrame (data=d)

but this would not be ideal as in my case I have 2200 columns in df . 但这不是理想的,因为在我的情况下,我在df有2200列。 Is there a more elegant solution? 有更优雅的解决方案吗?

You could use df.filter(regex=...) : 你可以使用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')

yields 产量

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

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

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