【问题标题】:Formatting a dictionary with Pandas Python使用 Pandas Python 格式化字典
【发布时间】:2022-01-27 00:35:53
【问题描述】:

我怎样才能重新排列字典a 的值,使其变成a2 的格式。所有columns 值都将转换为具有相应值的键。我怎样才能得到下面的预期输出?

代码:

a = {'columns': ['Month Average',
             'Month Median',
             'Month Max'],
 'data': [[0.0,
           0.0,
           0.0],
          [0.0,
           0.0,
           0.0],
          [-15.15,
           48.55384615384616,
           3.85]],
 'index': [2015, 2016, 2017]}

预期输出:

a = {
    'index': [2015, 2016, 2017],
    'Month Average':[0.0,0.0,0.0],
    'Month Median': [0.0,0.0,0.0],
    'Month Max': [-15.15,48.55384615384616,3.85]
     }

【问题讨论】:

  • 所以,这是一个奇怪的问题。你可以用 pandas 解决这个问题,看起来几乎是量身定做的,但是为什么?为什么会出现这种情况?

标签: python pandas dictionary indexing format


【解决方案1】:

第一个非熊猫解决方案:

a2 = {**{'index':a['index']}, **dict(zip(a['columns'], a['data']))}
print (a2)
{'index': [2015, 2016, 2017], 'Month Average': [0.0, 0.0, 0.0], 'Month Median': [0.0, 0.0, 0.0], 'Month Max': [-15.15, 48.55384615384616, 3.85]}

使用DataFrame构造函数:

df = pd.DataFrame(a['data'], index=a['index'], columns=a['columns'])
#if only data, index and columns keys use unpack **
df = pd.DataFrame(**a)
print (df)
      Month Average  Month Median  Month Max
2015           0.00      0.000000       0.00
2016           0.00      0.000000       0.00
2017         -15.15     48.553846       3.85

如需index栏目:

df = pd.DataFrame(**a).reset_index()
print (df)
   index  Month Average  Month Median  Month Max
0   2015           0.00      0.000000       0.00
1   2016           0.00      0.000000       0.00
2   2017         -15.15     48.553846       3.85

最后如果需要的话:

a2 = df.to_dict(orient='list')

【讨论】:

    猜你喜欢
    • 2021-12-21
    • 2021-08-07
    • 2011-02-14
    • 1970-01-01
    • 2017-10-24
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    相关资源
    最近更新 更多