在数据帧列中存储不同值的最佳方法?

2024-09-30 18:29:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难找出在一个pandas列中存储关于同一实体的多个数据的最佳或最简单的方法,举例来说,我有一些pandas数据帧,如下所示:

                a    b     c
     item0    2.0  NaN   1.1
     item1    1.3  2.2   2.0
     item2    1.4  NaN   NaN

                a    b     c
     item0    foo  bar   bar
     item1    bar  foo   bar
     item2    foo  foo   bar

我想将这些数据帧值聚合为一个,我没有成功地尝试将它们分配给多索引数据帧,这是我希望得到的:

                                   a                        b                         c
     item0    {prop1:2.0, prop2: foo}  {prop1:NaN, prop2: bar}   {prop1:1.1, prop2: bar}
     item1    {prop1:1.3, prop2: bar}  {prop1:2.2, prop2: foo}   {prop1:2.0, prop2: bar}
     item2    {prop1:1.4, prop2: foo}  {prop1:NaN, prop2: foo}   {prop1:NaN, prop2: bar}

或者

                         a              b              c
              prop1  prop2   prop1  prop2   prop1  prop2
     item0      2.0    foo     NaN    bar     1.1    bar
     item1      1.3    bar     2.2    foo     2.0    bar
     item2      1.4    foo     NaN    foo     NaN    bar

有没有一种简单的方法来聚合这些表单中的多个数据帧?你知道吗


Tags: 数据方法实体表单pandasfoobarnan
3条回答
df1 = pd.DataFrame(
    {'a': [2., 1.3, 1.4], 'b': [np.nan, 2.2, np.nan], 'c': [1.1, 2., np.nan]},
     index=['item0', 'item1', 'item2']
)
df2 = pd.DataFrame(
    {'a': ['foo', 'bar', 'foo'], 'b': ['bar', 'foo', 'foo'], 'c': ['bar'] * 3},
     index=['item0', 'item1', 'item2']
)


df1.columns = pd.MultiIndex.from_product([df1, ['prop1']])
df2.columns = pd.MultiIndex.from_product([df2, ['prop2']])

>>> pd.concat([df1, df2], axis=1).sort_index(axis=1, level=0)
          a           b           c      
      prop1 prop2 prop1 prop2 prop1 prop2
item0   2.0   foo   NaN   bar   1.1   bar
item1   1.3   bar   2.2   foo   2.0   bar
item2   1.4   foo   NaN   foo   NaN   bar

或者,连接数据帧(假设它们具有相同的列),分配一个新的多索引,然后恢复到原始顺序:

df = pd.concat([df1, df2], axis=1)
df.columns = pd.MultiIndex.from_tuples(product(['prop1', 'prop2'], df1))
df = df.swaplevel(0, 1, axis=1)[product(df1, ['prop1', 'prop2'])]

或者根据@ALollz使用的keys参数:

keys = ['prop1', 'prop2']
df = pd.concat([df1, df2], axis=1, keys=keys)
df = df.swaplevel(0, 1, axis=1)[product(df1, keys)]

Is there a simple way to aggregate multiple dataframes in these forms?

我理解您的问题,您正在尝试找出用于聚合或合并多个数据帧的索引。你知道吗

Pandas提供三种方式,concat()merge()join()

您需要指定索引Left,Inner,Right。 enter image description here

地址:Merge DF

如果这看起来像你要找的,我可以扩展这个答案。你知道吗

第二种选择更可取。当您将对象存储在数据帧(如字典)中时,会损失很多pandas效率。基本操作也变得更加困难。你知道吗

因为对齐在索引上,所以这只是带有keys参数的concat。如果您想在底部prop,那么可以交换级别。你知道吗

res = (pd.concat([df1, df2], axis=1, keys=['prop1', 'prop2'])
         .swaplevel(0,1, axis=1)
         .sort_index(axis=1))

print(res)
          a           b           c      
      prop1 prop2 prop1 prop2 prop1 prop2
item0   2.0   foo   NaN   bar   1.1   bar
item1   1.3   bar   2.2   foo   2.0   bar
item2   1.4   foo   NaN   foo   NaN   bar

相关问题 更多 >