我正在尝试将 YAML 文件中的数据获取到 Pandas DataFrame 中。以下面的例子
data.yml
:
---
- doc: "Book1"
reviews:
- reviewer: "Paul"
stars: "5"
- reviewer: "Sam"
stars: "2"
- doc: "Book2"
reviews:
- reviewer: "John"
stars: "4"
- reviewer: "Sam"
stars: "3"
- reviewer: "Pete"
stars: "2"
...
所需的 DataFrame 将如下所示:
doc reviews.reviewer reviews.stars
0 Book1 Paul 5
1 Book1 Sam 2
2 Book2 John 4
3 Book2 Sam 3
4 Book2 Pete 2
我尝试以不同的方式将 YAML 数据提供给 Pandas(如
with open('data.yml') as f: data = pd.DataFrame(yaml.load(f))
),但单元格始终包含嵌套的字典。此解决方案适用于一般 JSON 数据,但代码量相当多,而且似乎可能存在更简单的 YAML 解决方案。
是否有内置或 Pythonic 方法来非规范化 YAML,以便以这种方式转换为 Pandas Dataframe?
json_normalize
来展平字典:
pd.io.json.json_normalize(yaml.load(f), 'reviews', 'doc')
reviewer stars doc
0 Paul 5 Book1
1 Sam 2 Book1
2 John 4 Book2
3 Sam 3 Book2
4 Pete 2 Book2
现在使用上面会导致 FutureWarning:pandas.io.json.json_normalize 已弃用,请使用 pandas.json_normalize 代替
# lets say the yaml file is test_sample.yml
from pandas import json_normalize
from os import getcwd, path
from yaml import SafeLoader, load
path_to_yaml = path.join(getcwd(), ..., "test_sample.yaml")
with open(path_to_yaml) as yaml_file:
yaml_contents = load(path_to_file, Loader=SafeLoader)
yaml_df = json_normalize(yaml_contents)
+----------------+ +------------+ + +------------+ +-- ----------------+ |用户| |车辆 | |收费站| |交易 | +----------------+ +------------+ +------------+ +--- ---------------+ |用户 ID (PK) | |车辆ID | |收费站ID| |交易ID(PK)| |用户名 | |车牌| |地点 | |用户 ID (FK) | |密码 | |车辆类型 | |产能 | |车辆ID (FK) | |电子邮件 | |所有者 ID (FK)| |操作员ID | |收费站 ID (FK) | |名字 | +------------+ +------------+ |金额 | |姓氏 | |时间戳| |地址 | +------------------+ |电话号码 | |账户余额| |角色 | +----------------+