Python pandas:根据位置而不是索引值替换值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38776699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python pandas: replace values based on location not index value
提问by ramesh
Here is my df:
这是我的 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
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]
):
是否可以根据位置而不是索引值来做同样的事情,像这样,但它显示 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"
I get this warning :
我收到此警告:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
回答by ayhan
You can use get_loc to get the location of the column and pass that to iloc:
您可以使用 get_loc 获取列的位置并将其传递给 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
Or the other way around:
或者反过来:
df.loc[df.index[1], 's'] = 'B'