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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:38:03  来源:igfitidea点击:

Pandas: Change df column values based on condition with iloc

pythonpandasdataframe

提问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] > 1gives 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.ixwhich is a mix between .locand .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: .ixis now officially deprecated (since 0.20.0, see here)

编辑.ix现已正式弃用(自 0.20.0 起,请参见此处

You can use .locand 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

回答by piRSquared

generate a positional index by slicing np.arange(len(df))with a boolean mask.

通过np.arange(len(df))使用布尔掩码切片来生成位置索引。

df.iloc[np.arange(len(df))[df.values[:, 0] > 1], 0] = 10
df

enter image description here

在此处输入图片说明