gpt4 book ai didi

python-3.x - 按列名获取行值

转载 作者:行者123 更新时间:2023-12-05 03:41:52 25 4
gpt4 key购买 nike

我有以下数据框:

🐍 >>> data = {'seasons': ['season_2', 'season_3', 'season_4', 'season_5', 'season_6', 'season_7', 'season_1']}
🐍 >>> df = pd.DataFrame(data)
🐍 >>> df['season_1'] = 1
🐍 >>> df['season_2'] = 2
🐍 >>> df['season_3'] = 3
🐍 >>> df['season_4'] = 4
🐍 >>> df['season_5'] = 5
🐍 >>> df['season_6'] = 6
🐍 >>> df['season_7'] = 7
🐍 >>>
🐍 >>> df
seasons season_1 season_2 season_3 season_4 season_5 season_6 season_7
0 season_2 1 2 3 4 5 6 7
1 season_3 1 2 3 4 5 6 7
2 season_4 1 2 3 4 5 6 7
3 season_5 1 2 3 4 5 6 7
4 season_6 1 2 3 4 5 6 7
5 season_7 1 2 3 4 5 6 7
6 season_1 1 2 3 4 5 6 7

如何为给定行创建一个新列,该列的值在 seasons 中指定?例如我希望 season_values 的值为:

season_values = [2, 3, 4, 5, 6, 7, 1]

最佳答案

尝试:

df = df.assign(season_values = df.apply(lambda x: x[x['seasons']],1))
# df['season_values'] = df.apply(lambda x: x[x['seasons']],1)

通过 melt 的另一个选项:

melt = df.melt(['seasons'], ignore_index=False)
df['season_value'] = melt.loc[melt['seasons'] == melt['variable']]

关于python-3.x - 按列名获取行值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67548394/

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