我想知道是否有一种pandas
方法(内置的,或者通常更好)将一列记录(其中记录是List[dict]
)unest到DataFrame
中
样本数据:
import pandas as pd
expected = pd.DataFrame({
'A': [1, 1, 2],
'asset_id': ["aaa", "AAA", "bbb"],
'another_prop': [2, 3, 4]
})
df = pd.DataFrame({
'A':[1,2],
'B':[
[
{"asset_id": "aaa", "another_prop": 2},
{"asset_id": "AAA", "another_prop": 4}
],
[
{"asset_id": "bbb", "another_prop": 3}
]
]
})
我的尝试:
def unnest_records(df: pd.DataFrame, col: str) -> pd.DataFrame:
""" Unnests a column of records into a DataFrame."""
df_unnested = df.explode(col) # unnest records
records = df_unnested.pop(col) # 1 row per record
return pd.concat([df_unnested.reset_index(drop=True), pd.io.json.json_normalize(records)], axis=1)
输出:
>>> unnest_records(df, "B")
A asset_id another_prop
0 1 aaa 2
1 1 AAA 4
2 2 bbb 3
IIUC}和
explode
{set_index
或者正如@anky所指出的:
你也可以这样做
相关问题 更多 >
编程相关推荐