可以使用pandas的groupby方法和concat方法来实现按照不同的列将数据整理到DataFrame中。
例如,我们有以下数据:
import pandas as pd
df1 = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': [1, 2, 3, 4, 5, 6, 7, 8],
'D': [9, 10, 11, 12, 13, 14, 15, 16]})
df2 = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['three', 'two', 'one', 'one', 'two', 'two', 'one', 'three'],
'E': [17, 18, 19, 20, 21, 22, 23, 24],
'F': [25, 26, 27, 28, 29, 30, 31, 32]})
现在,将df1和df2按照A列进行分组,然后再按照B列进行分组,最后使用concat方法将它们合并到同一个DataFrame中:
grouped1 = df1.groupby('A')
grouped2 = df2.groupby('A')
df1_new = pd.concat([grouped1.get_group('foo').set_index('B')['C'], grouped2.get_group('foo').set_index('B')['E']], axis=1)
df2_new = pd.concat([grouped1.get_group('bar').set_index('B')['D'], grouped2.get_group('bar').set_index('B')['F']], axis=1)
result = pd.concat([df1_new, df2_new], keys=['foo', 'bar'])
这里的结果可以看作是按照A列将不同的数据分组,每个分组内按照B列将数据整理到不同的DataFrame中。最后使用concat方法将它们整合到同一个DataFrame中,最终的结果如下所示:
C E
B
foo one 1 19
two 3 21
下一篇:按照一列进行分组并按照日期排序