拆分数据框并创建新的数据框

时间:2016-03-25 19:18:00

标签: python numpy pandas

简单代码

  

我有一个数据帧df,我有一个数据帧,我分成3个相同大小的数据帧。但是我想用这3个数据帧创建一个数据帧。新数据帧的列是转换这3个数据帧,即将3栏

   In [4]: np.array_split(df, 3)
   Out[4]: 
     [ A    B         C         D
   0 foo  one -0.174067 -0.608579
   1 bar  one -0.860386 -1.210518
   2 foo  two  0.614102  1.689837,
      A      B         C         D
   3  bar  three -0.284792 -1.071160
   4  foo    two  0.843610  0.803712
   5  bar    two -1.514722  0.870861,
     A      B         C         D
   6 foo    one  0.131529 -0.968151
   7 foo  three -1.002946 -0.257468
   8 foo  three -1.002946 -0.257468]

1 个答案:

答案 0 :(得分:0)

<强>更新

切片和转置

In [2]: df
Out[2]:
   a  b  c
0  9  9  7
1  1  7  6
2  5  9  1
3  7  4  0
4  5  2  3
5  2  4  6
6  6  3  6
7  0  2  7
8  9  1  4
9  2  9  3

In [3]: dfs = [pd.DataFrame(a).T for a in np.array_split(df, 3)]

In [4]: dfs[0]
Out[4]:
   0  1  2  3
a  9  1  5  7
b  9  7  9  4
c  7  6  1  0

旧版

一种选择是使用它:

In [114]: dfs = [pd.DataFrame(a) for a in np.array_split(df, 3)]

In [115]: dfs[0]
Out[115]:
     a    b  c
0  NaN  7.0  0
1  0.0  NaN  4
2  2.0  NaN  4
3  1.0  7.0  0

In [116]: df
Out[116]:
     a    b  c
0  NaN  7.0  0
1  0.0  NaN  4
2  2.0  NaN  4
3  1.0  7.0  0
4  1.0  3.0  9
5  7.0  4.0  9
6  2.0  6.0  9
7  9.0  6.0  4
8  3.0  0.0  9
9  9.0  0.0  1