如何按索引顺序拆分pandas.DataFrame?

纽斯科勒

如果我有两个pandas.DataFrame具有相同的列。

df1 = pd.DataFrame(np.random.rand(5, 6), columns=list('abcdef'))
df2 = pd.DataFrame(np.random.rand(5, 6), columns=list('abcdef'))

我将它们合并为一个:

df = pd.concat([df1, df2], ignore_index = False)

现在不忽略索引值。

在不更改索引值的情况下执行了一些数据操作之后,如何才能反向返回串联,以便最终得到两个数据帧的列表?

BEN_YO

我建议keysconcat

df = pd.concat([df1, df2], ignore_index = False,keys=['df1','df2'])
df
Out[28]: 
              a         b         c         d         e         f
df1 0  0.426246  0.162134  0.231001  0.645908  0.282457  0.715134
    1  0.973173  0.854198  0.419888  0.617750  0.115466  0.565804
    2  0.474284  0.757242  0.452319  0.046627  0.935915  0.540498
    3  0.046215  0.740778  0.204866  0.047914  0.143158  0.317274
    4  0.311755  0.456133  0.704235  0.255057  0.558791  0.319582
df2 0  0.449926  0.330672  0.830240  0.861221  0.234013  0.299515
    1  0.552645  0.620980  0.313907  0.039247  0.356451  0.849368
    2  0.159485  0.620178  0.428837  0.315384  0.910175  0.020809
    3  0.687249  0.824803  0.118434  0.661684  0.013440  0.611711
    4  0.576244  0.915196  0.544099  0.750581  0.192548  0.477207

转换回

df1,df2=[y.reset_index(level=0,drop=True) for _, y in df.groupby(level=0)]
df1
Out[30]: 
          a         b         c         d         e         f
0  0.426246  0.162134  0.231001  0.645908  0.282457  0.715134
1  0.973173  0.854198  0.419888  0.617750  0.115466  0.565804
2  0.474284  0.757242  0.452319  0.046627  0.935915  0.540498
3  0.046215  0.740778  0.204866  0.047914  0.143158  0.317274
4  0.311755  0.456133  0.704235  0.255057  0.558791  0.319582

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

按其他索引的顺序对Pandas Dataframe进行排序

如何按索引对Pandas DataFrame排序?

如何按列拆分DataFrame

在具有multiindex的pandas Dataframe中,如何按顺序过滤?

如何从Pandas DataFrame中按索引值检索行?

如何按列和索引连接Pandas DataFrame?

按列表顺序对pandas DataFrame排序

Pandas DataFrame:按类型过滤列/索引

在 Pandas DataFrame 中按连续索引分组

如何更改 Pandas DataFrame 的索引

如何按行值将 DataFrame 拆分为多个 DataFrame?

按系列索引对Pandas DataFrame /系列进行索引

如何使用Pandas从DataFrame拆分列

Python Pandas:在 DataFrame 的特定列中按模式(跨行)拆分

如何使用规则在pandas DataFrame中按索引仅保留一组特定的行

pandas.DataFrame:如何按索引对齐/分组和排序数据?

Python Pandas DataFrame拆分

使用MultiIndex索引到Pandas DataFrame时保持顺序吗?

串联两个Pandas DataFrame,同时保持索引顺序

按特定顺序对Pandas DataFrame中的列进行排序

按特定顺序排序(情况:pandas DataFrame Groupby)

按日期顺序重新排列Pandas DataFrame日期列

如何从多索引字典构建 Pandas DataFrame

Pandas DataFrame:如何创建多列索引

Pandas Dataframe Mutli索引按级别和列值排序

按给定的行索引对 Pandas DataFrame 进行分组

当列名是整数时,按列号索引pandas DataFrame

按索引列上的条件过滤pandas Dataframe中的值

按条件获取Pandas Dataframe中元素的索引