【问题标题】:Create dataframes from unique value pairs by filtering across multiple columns通过跨多列过滤从唯一值对创建数据框
【发布时间】:2016-07-06 01:02:32
【问题描述】:

我想过滤多个列的值,为唯一值组合创建数据框。任何帮助将不胜感激。

这是我失败的代码(给定数据框 df):

dd = defaultdict(dict)  #create blank default dictionary
values_col1 = df.col1.unique()   #get the unique values from column 1 of df
for i in values_col1:
    dd[i] = df[(df['col1']==i)]    #for each unique value create a sorted df and put in in a dictionary
    values_col2 = dd[i].col2.unique() #get the unique values from column2 of df
    for m in values_col2:  
        dd[i][m] = dd[i][(dd[i]['col2']==m)]  #for each unique column2 create a sub dictionary

当我运行它时,我收到一条很长的错误消息。我不会在这里插入整个内容,但这里是其中的一部分:

C:\Anaconda3\lib\site-packages\pandas\indexes\base.py in get_loc(self, 键、方法、容限)1944 年尝试: -> 1945 返回 self._engine.get_loc(key) 1946 除了 KeyError:

...

ValueError: 传递的项目数错误 6,位置暗示 1

【问题讨论】:

  • 了解 numpy 排列。

标签: python pandas dataframe


【解决方案1】:

使用 pandas groupby 功能提取数据帧的唯一索引和相应行。

import pandas as pd
from collections import defaultdict

df = pd.DataFrame({'col1': ['A']*4 + ['B']*4,
                   'col2': [0,1]*4,
                   'col3': np.arange(8),
                   'col4': np.arange(10, 18)})

dd = defaultdict(dict)
grouped = df.groupby(['col1', 'col2'])
for (c1, c2), g in grouped:
    dd[c1][c2] = g

这是生成的df

  col1  col2  col3  col4
0    A     0     0    10
1    A     1     1    11
2    A     0     2    12
3    A     1     3    13
4    B     0     4    14
5    B     1     5    15
6    B     0     6    16
7    B     1     7    17

这是提取的dd(嗯,真的是dict(dd)

{'B': {0:   col1  col2  col3  col4
          4    B     0     4    14
          6    B     0     6    16,
       1:   col1  col2  col3  col4
          5    B     1     5    15
          7    B     1     7    17},
 'A': {0:   col1  col2  col3  col4
          0    A     0     0    10
          2    A     0     2    12,
       1:   col1  col2  col3  col4
          1    A     1     1    11
          3    A     1     3    13}}

(我不知道您的用例是什么,但您最好还是不要将 groupby 对象解析为字典)。

【讨论】:

  • 感谢 Alberto,您是如何在上面的代码中创建“分组”的?
  • 抱歉,忘记复制那行了。已编辑。
  • 感谢优雅的解决方案!
猜你喜欢
  • 2017-04-01
  • 1970-01-01
  • 2021-01-22
  • 2022-10-30
  • 1970-01-01
  • 2019-01-20
  • 1970-01-01
  • 2019-05-21
  • 2020-06-15
相关资源
最近更新 更多