Pandas:使用 iloc 根据条件更改 df 列值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41173788/
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
Pandas: Change df column values based on condition with iloc
提问by lotrus28
Take a dataframe, say
取一个数据框,说
df = pd.DataFrame([[1,2],[3,4],[5,6]],columns=['A','B'])
A B
0 1 2
1 3 4
2 5 6
Now I want to change cells in the first column.
I can do it this way:
现在我想更改第一列中的单元格。
我可以这样做:
df.loc[df['A'] > 1,'A'] = 10
A B
0 1 2
1 10 4
2 10 6
But what if i don't have any column names?
df.iloc[:,0] > 1
gives me the same mask as df['A'] > 1
And while
但是如果我没有任何列名怎么办?
df.iloc[:,0] > 1
给了我df['A'] > 1
和 And while一样的面具
df.loc[df.iloc[:,0] > 1,'A'] = 10
works perfectly fine,
工作得很好,
using
使用
df.iloc[df.iloc[:,0] > 1,1] = 10
on the initial df somehow return this error:
在初始 df 以某种方式返回此错误:
NotImplementedError: iLocation based boolean indexing on an integer type is not available
NotImplementedError: 基于 iLocation 的整数类型的布尔索引不可用
Is there a way to change specific cells using only integer indexing?
有没有办法仅使用整数索引来更改特定单元格?
采纳答案by Julien Marrec
Use DataFrame.ix
which is a mix between .loc
and .iloc
:
使用DataFrame.ix
这之间的混合.loc
和.iloc
:
.ix[] supports mixed integer and label based access. It is primarily label based, but will fall back to integer positional access unless the corresponding axis is of integer type.
.ix[] 支持混合整数和基于标签的访问。它主要基于标签,但除非相应的轴是整数类型,否则将回退到整数位置访问。
In your case:
在你的情况下:
In [1]: df.ix[df.iloc[:,0]>1,1] = 10
In [2]: df
Out[2]:
A B
0 1 2
1 3 10
2 5 10
Edit: .ix
is now officially deprecated (since 0.20.0, see here)
编辑:.ix
现已正式弃用(自 0.20.0 起,请参见此处)
You can use .loc
and make use of df.columns[i]
instead, eg. the equivalent to the above is:
您可以使用.loc
和利用df.columns[i]
,例如。等价于上面的是:
df.loc[df.iloc[:,0]>1,df.columns[1]] = 10