python - 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,)
所以我要确定的是什么是规范化数据的适当方法,其中有时该数据的子集没有值。
我已经阅读了关于规范化数据子集然后合并的内容,但是我还没有遇到一个我可以很容易理解的具体示例。
提前感谢您提供的任何指导。
解决方案
推荐阅读
- c# - 使用 Entity Framework Core 2.0 更改或重命名列名而不丢失数据
- java - 如何避免swagger codegen接口中的默认方法实现?
- vba - 禁止“下载文件”框
- javascript - 根据 v-select 选项更改 v-slider 和 v-text-field 中显示的值
- html - 如何在打开时仅在模式弹出窗口内限制 Tab 键按下?
- angular - 使用 Angular 6 在嵌套组件中访问 RouterLinkActive
- java - 在 springboot 1.5->2.0 迁移期间 Postgresql 枚举中断
- eclipse - HTTP 状态 405 - 方法不允许(仅适用于使用 tomcat 服务器的球衣中的 DELETE 方法)
- azure-active-directory - Azure AD - SAML 单一注销 - 不支持的绑定 HTTP-POST
- awk - 语法错误搜索模式并在单行中使用 awk 命令打印下 5 行