Python 熊猫基于重复索引数据帧创建多个数据帧
如果索引中有重复的数据帧,如何创建索引中没有重复的数据帧集 更准确地说,给定数据帧:Python 熊猫基于重复索引数据帧创建多个数据帧,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,如果索引中有重复的数据帧,如何创建索引中没有重复的数据帧集 更准确地说,给定数据帧: a b 1 1 6 1 2 7 2 3 8 2 4 9 2 5 0 我想要一个数据帧列表作为输出: a b 1 1 6 2 3 8 a b 1 2 7 2 4 9 a b 2 5 0 这需要根据重复的数量扩展到所需的任意多个数据帧。另一种方法是使用pd.DataFrame.groupby.nth: import numpy as
a b
1 1 6
1 2 7
2 3 8
2 4 9
2 5 0
我想要一个数据帧列表作为输出:
a b
1 1 6
2 3 8
a b
1 2 7
2 4 9
a b
2 5 0
这需要根据重复的数量扩展到所需的任意多个数据帧。另一种方法是使用
pd.DataFrame.groupby.nth
:
import numpy as np
g = df.groupby(df.index)
cnt = np.bincount(df.index).max()
dfs = [g.nth(i) for i in range(cnt)]
输出:
[ a b
1 1 6
2 3 8,
a b
1 2 7
2 4 9,
a b
2 5 0]
用于自定义组,然后将组转换为字典:
df = dict(tuple(df.groupby(df.groupby(level=0).cumcount())))
print (df)
{0: a b
1 1 6
2 3 8, 1: a b
1 2 7
2 4 9, 2: a b
2 5 0}
print (dfs[0])
a b
1 1 6
2 3 8
或转换为数据帧列表:
dfs = [x for i, x in df.groupby(df.groupby(level=0).cumcount())]
print (dfs)
[ a b
1 1 6
2 3 8, a b
1 2 7
2 4 9, a b
2 5 0]
谢谢这是一个很好的解决方案谢谢!接受,因为它会立即将索引和输出自动排序为列表:P
df=df.reset_index()
dfs=[]
while not df.empty:
dfs.append(df[~df.duplicated('index',keep='first')].set_index('index'))
df=df[df.duplicated('index',keep='first')]
#dfs will have all your dataframes