gpt4 book ai didi

python - Pandas :如何设置标签列的最后一行值?

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

我有一个数据框

x = pd.DataFrame([11, 22, 33, 44], columns=['K'])
x
K
0 11
1 22
2 33
3 44

我想设置 K 列最后一行的值。这与 Copy-Warning 一起使用:

x['K'].iloc[-1] = 999

我试过 .loc,但 -1 被视为标签,并且由于我的索引很好(从 0 开始,递增 1),将创建一个新行。

正确的做法是什么?

谢谢!

最佳答案

如果需要按位置设置两个位置 - 对于索引和列,那么您可以通过 Index.get_loc 按列名 K 获取位置:

x.iloc[-1, x.columns.get_loc('K')] = 999
#alternative for set scalar
#x.iat[-1, x.columns.get_loc('K')] = 999

或通过获取索引的最后一个值的标签设置(索引值必须是唯一的):

x.loc[x.index[-1], 'K'] = 999
#alternative for set scalar
#x.at[x.index[-1], 'K'] = 999

关于python - Pandas :如何设置标签列的最后一行值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59250143/

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