gpt4 book ai didi

pandas - 设置为 Pandas DataFrame 的第一行

转载 作者:行者123 更新时间:2023-12-05 00:51:04 24 4
gpt4 key购买 nike

我想在某个列中为 Pandas DataFrame 的前 n 行设置一个值。

>>> example = pd.DataFrame({'number':range(10),'name':list('aaabbbcccc')},index=range(20,0,-2)) # nontrivial index
>>> example
name number
20 a 0
18 a 1
16 a 2
14 b 3
12 b 4
10 b 5
8 c 6
6 c 7
4 c 8
2 c 9

我想将第一行的“数字”设置为第 5 行到数字 19。我真正想要的是将“数字”的最低值设置为该值,所以我只先排序。
如果我的索引是微不足道的,我可以做
example.loc[:5-1,'number'] = 19 # -1 for inclusive indexing
# or
example.ix[:5-1,'number'] = 19

但由于它不是,这将产生以下工件(其中选择了最多 4 的所有索引值):
>>> example
name number
20 a 19
18 a 19
16 a 19
14 b 19
12 b 19
10 b 19
8 c 19
6 c 19
4 c 19
2 c 9

使用 .iloc[] 会很好,只是它不接受列名。
example.iloc[:5]['number'] = 19

有效,但给出了 SettingWithCopyWarning。

我目前的解决方案是:
>>> example.sort_values('number',inplace=True)
>>> example.reset_index(drop=True,inplace=True)
>>> example.ix[:5-1,'number'] = 19
>>> example
name number
0 a 19
1 a 19
2 a 19
3 b 19
4 b 19
5 b 5
6 c 6
7 c 7
8 c 8
9 c 9

而且由于我必须对几列重复此操作,因此我必须这样做几次并每次都重置索引,这也会花费我的索引(但没关系)。

有没有人有更好的解决方案?

最佳答案

我会使用 .iloc ,因为如果重复某些索引, .loc 可能会产生意想不到的结果。

example.iloc[:5, example.columns.get_loc('number')] = 19

关于pandas - 设置为 Pandas DataFrame 的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44792152/

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