Python Pandas:根据位置而非索引值替换值 [英] Python pandas: replace values based on location not index value

查看:83
本文介绍了Python Pandas:根据位置而非索引值替换值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的df:

In[12]: df  = pd.DataFrame(data = list("aabbcc"), columns = ["s"], index=range(11,17))
In[13]: df
Out[13]: 
    s
11  a
12  a
13  b
14  b
15  c
16  c

现在,根据索引值替换值:

Now, replacing values based on index values:

In[14]: df.loc[11, "s"] = 'A'
In[15]: df
Out[15]: 
    s
11  A
12  a
13  b
14  b
15  c
16  c
In[16]: df.ix[12, "s"] = 'B'
In[17]: df
Out[17]: 
    s
11  A
12  B
13  b
14  b
15  c
16  c

是否可以基于位置而不是索引值执行相同的操作,类似这样,但是它显示ValueError(ValueError: Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array]):

Is it possible to do the same based on position not index value, something like this, but it shows ValueError (ValueError: Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array]):

In[18]: df.iloc[1, "s"] = 'b'

而且,如果我尝试这样的事情:

And, if I try something like this:

df.s.iloc[1] = "b"

我收到此警告:

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

推荐答案

您可以使用get_loc获取列的位置并将其传递给iloc:

You can use get_loc to get the location of the column and pass that to iloc:

df.iloc[1, df.columns.get_loc('s')] = 'B'

df
Out: 
    s
11  a
12  B
13  b
14  b
15  c
16  c

反之亦然:

df.loc[df.index[1], 's'] = 'B'

这篇关于Python Pandas:根据位置而非索引值替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆