Pandas Split DataFrame 使用行索引

新手上路,请多包涵

我想使用行索引按不均匀的行数拆分数据帧。

下面的代码:

 groups = df.groupby((np.arange(len(df.index))/l[1]).astype(int))

仅适用于统一行数。

 df

a b c
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7

l = [2, 5, 7]

df1
1 1 1
2 2 2

df2
3,3,3
4,4,4
5,5,5

df3
6,6,6
7,7,7

df4
8,8,8

原文由 Pradeep Tummala 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 465
2 个回答

您可以使用列表推导式,首先对您的列表进行一些修改。

 print(df)

   a  b  c
0  1  1  1
1  2  2  2
2  3  3  3
3  4  4  4
4  5  5  5
5  6  6  6
6  7  7  7
7  8  8  8

l = [2,5,7]
l_mod = [0] + l + [max(l)+1]

list_of_dfs = [df.iloc[l_mod[n]:l_mod[n+1]] for n in range(len(l_mod)-1)]

输出:

 list_of_dfs[0]

   a  b  c
0  1  1  1
1  2  2  2

list_of_dfs[1]

   a  b  c
2  3  3  3
3  4  4  4
4  5  5  5

list_of_dfs[2]

   a  b  c
5  6  6  6
6  7  7  7

list_of_dfs[3]

   a  b  c
7  8  8  8

原文由 Scott Boston 发布,翻译遵循 CC BY-SA 4.0 许可协议

我认为这就是您所需要的:

 df = pd.DataFrame({'a': np.arange(1, 8),
                  'b': np.arange(1, 8),
                  'c': np.arange(1, 8)})
df.head()
    a   b   c
0   1   1   1
1   2   2   2
2   3   3   3
3   4   4   4
4   5   5   5
5   6   6   6
6   7   7   7

last_check = 0
dfs = []
for ind in [2, 5, 7]:
    dfs.append(df.loc[last_check:ind-1])
    last_check = ind

虽然列表理解比 for 循环更有效,但如果您的索引列表中没有模式,则 last_check 是必需的。

 dfs[0]

    a   b   c
0   1   1   1
1   2   2   2

dfs[2]

    a   b   c
5   6   6   6
6   7   7   7

原文由 Mohit Motwani 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题