gpt4 book ai didi

python - 如何在 pandas 数据框中用 Series 压平列?

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:03 25 4
gpt4 key购买 nike

我有一个 pandas df,我需要展平系列列

data = pd.DataFrame([['TRAN',[{'Name':'Ben','Age':'24'}],'T','Good'],
['LMI',[{'Name':'Zoe','Age':'32'}],'U','Better'],
['ARN',[{'Name':'Jack','Age':'28'}],'V','Best']
],
columns=['Type', 'Applicant', 'Decision', 'Action'])

data 是 pandas dataframe,Applicant column 是一个 Series,

#data
type(data)
Out[25]: pandas.core.frame.DataFrame
#Applicant Column
type(data.Applicant)
Out[26]: pandas.core.series.Series

我需要展平系列并将列名转换为 'Type''Applicant.Name''Applicant.Age', '决定', '行动'.

最佳答案

没有 apply 的解决方案(如果性能很重要)将是:

data=(pd.DataFrame(data.pop('Applicant').str[0].values.tolist())
.add_prefix('Applicant.').join(data))

  Applicant.Age Applicant.Name  Type Decision  Action
0 24 Ben TRAN T Good
1 32 Zoe LMI U Better
2 28 Jack ARN V Best

关于python - 如何在 pandas 数据框中用 Series 压平列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56664194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com