这是创建我的系列的方法:
import pandas as pd
stk = pd.Series([[{'stock': 'AAPL', 'amt': 23},
{'stock': 'DIS', 'amt': 52}],
[{'stock': 'IBM', 'amt': 78},
{'stock': 'MSFT', 'amt': 34}]],
index=['2023-12-16','2023-12-17'])
print(stk)
打印输出如下所示: 2023-12-16 [{'stock': 'AAPL', 'amt': 23}, {'stock': 'DIS', 'amt': 52}] 2023-12-17 [{'stock': 'IBM', 'amt': 78}, {'stock': 'MSFT', 'amt': 34}]
当我使用以下代码将其转换为 DataFrame 时:
df = pd.concat([pd.DataFrame(d) for d in stk])
print(df)
我得到这个输出:
stock amt
0 AAPL 23
1 DIS 52
0 IBM 78
1 MSFT 34
系列的日期索引消失了。这是我想要的输出:
dt stock amt
2023-12-16 AAPL 23
2023-12-16 DIS 52
2023-12-17 IBM 78
2023-12-17 MSFT 34
有人可以帮我吗?
这是一个快速的替代方案。
flatten
首先使用 explode
扩展系列,然后将每个单元格(从字典)扩展为系列 -
stk.explode().apply(pd.Series)
stock amt
2023-12-16 AAPL 23
2023-12-16 DIS 52
2023-12-17 IBM 78
2023-12-17 MSFT 34