由于存在 NaN
值,上述构造方法会失败。这里提供一个使用 pandas 中 <code>str</code>/<code>Series</code>方法的可能解决方案:
out = df["stats"].str[0].apply(pd.Series).drop(0, axis=1)
或者采用如下方式:
stats = df["stats"].str[0]
templ = dict.fromkeys(["city", "last_time"], pd.NA) # 使用 pd.NA 替换 None
out = stats.where(stats.notnull(), templ).apply(pd.Series)
输出结果为:
print(out)
city last_time
0 <NA> 1234567.00
1 <NA> NaN
2 Seattle 45678999876.00
[3 rows x 2 columns]
使用的输入数据为:
import pandas as pd
df = pd.DataFrame(
{
"stats": [
[{"city": None, "last_time": 1234567}],
[],
[{"city": "Seattle", "last_time": 45678999876}]
]
}
)