gpt4 book ai didi

python - 包含 pandas 数据框中单个元素列表的正确列

转载 作者:行者123 更新时间:2023-11-30 22:26:40 24 4
gpt4 key购买 nike

我有以下内容。数据框:

      a_name  Season    yl
yl
4.939 cherka 2000.0 [4.939]
4.441 cherka 2001.0 [4.441]
4.320 cherka 2002.0 [4.32]
3.718 cherka 2003.0 [3.718]
4.533 cherka 2004.0 [4.533]

如何将其转换为:

      a_name  Season    yl
yl
4.939 cherka 2000.0 4.939
4.441 cherka 2001.0 4.441
4.320 cherka 2002.0 4.32
3.718 cherka 2003.0 3.718
4.533 cherka 2004.0 4.533

我通过这样做得到了它:

df.groupby(['a_name', 'Season', 'yl'])['yl'].unique().reset_index(level=[0,1])

最佳答案

扩展我的评论,使用.str[0]:

df

a_name Season yl
yl
4.939 cherka 2000.0 [4.939]
4.441 cherka 2001.0 [4.441]
4.320 cherka 2002.0 [4.32]
3.718 cherka 2003.0 [3.718]
4.533 cherka 2004.0 [4.533]

df['yl'] = df['yl'].str[0]
df

a_name Season yl
yl
4.939 cherka 2000.0 4.939
4.441 cherka 2001.0 4.441
4.320 cherka 2002.0 4.320
3.718 cherka 2003.0 3.718
4.533 cherka 2004.0 4.533
<小时/>

您可以选择使用分配 ( piRsquared's suggestion ) 创建副本:

df_new = df.assign(df['yl'].str[0])

df_new

a_name Season yl
yl
4.939 cherka 2000.0 4.939
4.441 cherka 2001.0 4.441
4.320 cherka 2002.0 4.320
3.718 cherka 2003.0 3.718
4.533 cherka 2004.0 4.533

关于python - 包含 pandas 数据框中单个元素列表的正确列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47164230/

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