假设我有以下 DataFame:
df = pd.DataFrame(
{
'id':[112, 130, 200],
'name':['Lara', 'Kasia', 'Rocco'],
'level/income':[{1:400, 2:800}, {1:100}, {1:1000, 2:2000, 3:5000}]
}
)
我希望这是最终结果:
我尝试自己做到这一点,但我失败了。我试图通过查找哪个 id
和 name
会出现多次来重新创建原始 DataFrame,但事实证明这太多了。
len_need = []
id2 = []
name2 = []
level2 = []
income2 = []
for index,row in df.iterrows():
len_need.append(len(row['level/income']))
我确信有更好的方法来做到这一点。
最佳答案
试试这个:
(df.set_index(['id', 'name'])
.squeeze()
.apply(pd.Series)
.rename_axis('level', axis=1)
.stack()
.reset_index(name='income'))
>>>
id name level income
0 112 Lara 1 400.0
1 112 Lara 2 800.0
2 130 Kasia 1 100.0
3 200 Rocco 1 1000.0
4 200 Rocco 2 2000.0
5 200 Rocco 3 5000.0
关于python - 如何在 Pandas 列中提取 JSON 数据并通过堆叠来构建它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72610834/