简体   繁体   English

按子列将 Dataframe 拆分为多个 Dataframe

[英]Split Dataframe to multiple Dataframes by sub columns

I could not find an elegant way to split this table:我找不到一种优雅的方式来拆分这张桌子:

Open              Close                High 
 stock1 stock2     stock1 stock2        stock1 stock2
  ..     ..         ..      ..           ..     ..

Where stocks are sub columns, into multiple tables each for a stock, so first table is股票是子列,分成多个表,每个表对应一个股票,所以第一个表是

df_stock1 df_stock1

   Open Close High

so a table/dataframe for each stock ( could be > 2 ) then return an array of those dataframes .所以每个股票的表/数据框(可能> 2)然后返回这些dataframes的数组。

You could do something like this.你可以做这样的事情。 Here's a fictiv dataframe:这是一个虚构的 dataframe:

import pandas as pd
import numpy as np
np.random.seed(123)
df = pd.DataFrame(np.random.randint(1, 10, (6, 6)),
                  columns=pd.MultiIndex.from_product([['Open', 'Close', 'High'],
                                                      ['Stock1', 'Stock2']]))

which prints:打印:

Open         Close          High       
  Stock1 Stock2 Stock1 Stock2 Stock1 Stock2
0      3      3      7      2      4      7
1      2      1      2      1      1      4
2      5      1      1      5      2      8
3      4      3      5      8      3      5
4      9      1      8      4      5      7
5      2      6      7      3      2      9

Then to split your multi-index df, do the following, using groupby and DataFrame.xs:然后拆分您的多索引 df,使用 groupby 和 DataFrame.xs 执行以下操作:

Split = {idx: df_sub.xs(idx, level=1, axis=1) for idx,df_sub in df.groupby(level=1, axis=1)}
print(Split['Stock1'])

where df_sub refers to the first-level of the multiindex df.其中df_sub指的是多索引 df 的第一级。 This givess:这给出了:

 Open  Close  High
0     3      7     4
1     2      2     1
2     5      1     2
3     4      5     3
4     9      8     5
5     2      7     2

and

Split2 = {idx: df_sub.xs(idx, level=1, axis=1) for idx,df_sub in df.groupby(level=1, axis=1)}
print(Split2['Stock2'])

prints:印刷:

 Open  Close  High
0     3      2     7
1     1      1     4
2     1      5     8
3     3      8     5
4     1      4     7
5     6      3     9

EDIT Other levels编辑其他级别

Similarily, if you want all the Open stocks, you can do this:同样,如果你想要所有的 Open 股票,你可以这样做:

Split_open = {idx: df_sub.xs(idx, level=0, axis=1) for idx,df_sub in df.groupby(level=0, axis=1)}
print(Split_open['Open'])

which returns:返回:

   Stock1  Stock2
0       3       3
1       2       1
2       5       1
3       4       3
4       9       1
5       2       6

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

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