【发布时间】:2020-02-18 20:58:42
【问题描述】:
在查看SO 上的类似问题后,我一直无法找到使用嵌套字典对 DataFrame 格式化的解决方案,以获得所需的结果。
作为 Pandas 的新手和 Python 的新手,我花了两天的大部分时间尝试各种潜在的解决方案,但都失败了(json_normalize、dictionary flattening、pd.concat 等)。
我有一个从 API 调用创建 DataFrame 的方法:
def make_dataframes(self):
# removed non-related code
self._data_frame_counts = pd.DataFrame({
'Created': (self._data_frame_30days.count()['Created']),
'Closed': (self._data_frame_30days.count()['Closed']),
'Owner':
(self._data_frame_30days['Owner'].value_counts().to_dict()),
'Resolution':
(self._data_frame_30days['Resolution'].value_counts().to_dict()),
'Severity':
(self._data_frame_30days['Severity'].value_counts().to_dict())
})
从 Pandas value_count/s 写入嵌套字典:
{'Created': 35,
'Closed': 6,
'Owner': {'aName': 30, 'first.last': 3, 'last.first': 2},
'Resolution': {'TruePositive': 5, 'FalsePositive': 1},
'Severity': {2: 31, 3: 4}}
执行后的样子:
Created Closed Owner Resolution Severity
aName 35 6 30.0 NaN NaN
first.last 35 6 3.0 NaN NaN
last.first 35 6 2.0 NaN NaN
TruePositive 35 6 NaN 5.0 NaN
FalsePositive 35 6 NaN 1.0 NaN
2 35 6 NaN NaN 31.0
3 35 6 NaN NaN 4.0
我希望它看起来像下面这样。数据与轴准确对齐并说明字典中不存在但可能在未来运行中存在的缺失数据点。
Created Closed Owner Resolution Severity
total 35 6 NaN NaN NaN
aName NaN NaN 30 NaN NaN
first.last NaN NaN 3 NaN NaN
last.first NaN NaN 2 NaN NaN
anotherName NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN 0
2 NaN NaN NaN NaN 31
3 NaN NaN NaN NaN 4
second.Name NaN NaN NaN NaN NaN
third.name NaN NaN NaN NaN NaN
TruePositive NaN NaN NaN 5 NaN
FalsePositive NaN NaN NaN 1 NaN
【问题讨论】: