首页 > 解决方案 > Python 中的 Pandas DataFrames:如何展平数据而不丢失某些数据缺失的行?(json_normalize, where 函数)

问题描述

我刚刚开始在 Python 中学习 Pandas 和 DataFrames,虽然我的用例是获取 EC2 EBS 卷数据并将其展平为 CSV,其中有些卷有附件数据,有些则没有,但我想做的是完全使用 Pandas 来做到这一点(而不是事先迭代数据以添加丢失的虚拟数据)。

所以这是我能想到的最简单的用例:

import pandas as pd

states = [{'state': 'Florida',
           'shortname': 'FL',
           'counties': [{'name': 'Dade', 'population': 12345},
                        {'name': 'Broward', 'population': 40000},
                        {'name': 'Palm Beach', 'population': 60000}]},
          {'state': 'Ohio',
           'shortname': 'OH',
           'counties': [{'name': 'Summit', 'population': 1234},
                        {'name': 'Cuyahoga', 'population': 1337}]},
          {'state': 'New York',
           'shortname': 'NY',
           'counties': []}]

counties_normalized_data = pd.json_normalize(data=states, record_path='counties', record_prefix='county.', meta=['state', 'shortname'])

print(counties_normalized_data)

这导致:

  county.name  county.population    state shortname
0        Dade              12345  Florida        FL
1     Broward              40000  Florida        FL
2  Palm Beach              60000  Florida        FL
3      Summit               1234     Ohio        OH
4    Cuyahoga               1337     Ohio        OH

虽然这是有道理的,但我不想完全失去纽约。相反,我想保留纽约并将county.name 和county.population 设置为“N'A”。

因此,我开始使用 中的where函数DataFrame,但您可能已经知道,除非所有州都获得完全相同数量的县,否则它不会起作用。例如:

import pandas as pd

states = [{'state': 'Florida',
           'shortname': 'FL',
           'counties': [{'name': 'Dade', 'population': 12345},
                        {'name': 'Broward', 'population': 40000},
                        {'name': 'Palm Beach', 'population': 60000}]},
          {'state': 'Ohio',
           'shortname': 'OH',
           'counties': [{'name': 'Summit', 'population': 1234},
                        {'name': 'Cuyahoga', 'population': 1337}]},
          {'state': 'New York',
           'shortname': 'NY',
           'counties': []}]

df = pd.DataFrame(states)


df['counties'] = df['counties'].where(df['counties'].str.len() > 0, [{'name': 'Westchester', 'population': 3456}, {'name': 'Putnam', 'population': 1000}])

这导致以下异常:

ValueError: operands could not be broadcast together with shapes (3,) (3,) (2,)

所以我要确定的是什么是规范化数据的适当方法,其中有时该数据的子集没有值。

我已经阅读了关于规范化数据子集然后合并的内容,但是我还没有遇到一个我可以很容易理解的具体示例。

提前感谢您提供的任何指导。

标签: pythonpandasdataframe

解决方案


推荐阅读