这个解决方案有点难读,但在我的测试中它是有效的。第一步是从dict的顶级列表构建一个临时数据框,其中每个dict(可能为空)表示原始电子表格中的一行。
假设你的字典命名为
d
:
import pandas as pd
from pandas.io.json import json_normalize
temp = pd.DataFrame.from_dict(d['rowData'])
temp
values
0 [{}, {'note': 'B1 notes'}, {}, {}, {'note': 'E1 notes'}]
1 NaN
2 NaN
3 [{}, {}, {}, {'note': 'D4 notes'}]
4 NaN
5 NaN
6 [{}, {'note': 'B7 notes'}]
# JSON-normalize each non-null row
res = (pd.DataFrame(temp['values'].map(lambda x:
json_normalize(x).values.flatten()
if x is not np.nan else [np.nan])
.values
.tolist()
)
).fillna('')
res.index = range(1, res.shape[0]+1)
res.columns = list('ABCDE')
res
A B C D E
1 B1 notes E1 notes
2
3
4 D4 notes
5
6
7 B7 notes