python - 多索引 Pandas 数据框到字典

标签 python pandas dictionary multi-index

我有一个数据框如下:

raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
    'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
    'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],
    'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
    'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}

df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore'])

如果我按两列分组并计算大小,

df.groupby(['regiment','company']).size()

我得到以下信息:

regiment    company
Dragoons    1st        2
            2nd        2
Nighthawks  1st        2
            2nd        2
Scouts      1st        2
            2nd        2
dtype: int64

我想要的输出是一个字典,如下所示:

{'Dragoons':{'1st':2,'2nd':2},
 'Nighthawks': {'1st':2,'2nd':2}, 
  ... }

我尝试了不同的方法,但都无济于事。有没有相对干净的方法来实现上述目标?

非常感谢您!!!!

最佳答案

您可以添加 Series.unstackDataFrame.to_dict :

d = df.groupby(['regiment','company']).size().unstack().to_dict(orient='index')
print (d)
{'Dragoons': {'2nd': 2, '1st': 2}, 
 'Nighthawks': {'2nd': 2, '1st': 2}, 
 'Scouts': {'2nd': 2, '1st': 2}}

另一个解决方案,与另一个答案非常相似:

from collections import Counter

df = {i: dict(Counter(x['company'])) for i, x in df.groupby('regiment')}
print (df)
{'Dragoons': {'2nd': 2, '1st': 2}, 
'Nighthawks': {'2nd': 2, '1st': 2}, 
'Scouts': {'2nd': 2, '1st': 2}}

但如果使用第一种解决方案,NaN 就会有问题(这取决于数据)

示例:

raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
    'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '3rd'],
    'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],
    'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
    'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}

df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore'])
print (df)
      regiment company      name  preTestScore  postTestScore
0   Nighthawks     1st    Miller             4             25
1   Nighthawks     1st  Jacobson            24             94
2   Nighthawks     2nd       Ali            31             57
3   Nighthawks     2nd    Milner             2             62
4     Dragoons     1st     Cooze             3             70
5     Dragoons     1st     Jacon             4             25
6     Dragoons     2nd    Ryaner            24             94
7     Dragoons     2nd      Sone            31             57
8       Scouts     1st     Sloan             2             62
9       Scouts     1st     Piger             3             70
10      Scouts     2nd     Riani             2             62
11      Scouts     3rd       Ali             3             70

df1 = df.groupby(['regiment','company']).size().unstack()
print (df1)
company     1st  2nd  3rd
regiment                 
Dragoons    2.0  2.0  NaN
Nighthawks  2.0  2.0  NaN
Scouts      2.0  1.0  1.0

d = df1.to_dict(orient='index')
print (d)
{'Dragoons': {'3rd': nan, '2nd': 2.0, '1st': 2.0}, 
'Nighthawks': {'3rd': nan, '2nd': 2.0, '1st': 2.0}, 
'Scouts': {'3rd': 1.0, '2nd': 1.0, '1st': 2.0}}

然后是必要的使用:

d = {i: dict(Counter(x['company'])) for i, x in df.groupby('regiment')}
print (d)
{'Dragoons': {'2nd': 2, '1st': 2}, 
'Nighthawks': {'2nd': 2, '1st': 2},
 'Scouts': {'3rd': 1, '2nd': 1, '1st': 2}}

或另一个John Galt回答。

关于python - 多索引 Pandas 数据框到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44823418/

相关文章:

python - Pandas - 检查两个日期是否与确定的条件相同(另外两个变量)并执行操作

dictionary - 在 Kotlin 中将 `Throwable?` 映射到 `Result<Unit>`

python - 将相同的键值附加到字典列表中

python - 将数据帧切成间隔以进行统计分析 | Python

python - K均值: Reassign data point to second nearest?

javascript - 使用 Qlik Engine JSON API 导出可视化数据

python - 如何在webapp中实现标签?

Python:通过添加累计股息并取复合年增长率(CAGR)来计算总返回

python - 迭代字典中字典的键内的值

python - Linux - 存储仅具有用户权限的与用户无关的数据