2016-12-15 52 views
2

變化DF列的值取一個數據幀,說
熊貓:根據病情與ILOC

df = pd.DataFrame([[1,2],[3,4],[5,6]],columns=['A','B']) 

    A B 
0 1 2 
1 3 4 
2 5 6 

現在我想改變細胞的第一列。
我能做到這樣:

df.loc[df['A'] > 1,'A'] = 10 

    A B 
0 1 2 
1 10 4 
2 10 6 

但如果我沒有任何列名?
df.iloc[:,0] > 1給我相同的掩模作爲df['A'] > 1
雖然

df.loc[df.iloc[:,0] > 1,'A'] = 10 

工作完全正常,

使用

df.iloc[df.iloc[:,0] > 1,1] = 10 

初始DF莫名其妙地返回此錯誤:

NotImplementedError: iLocation based boolean indexing on an integer type is not available

有沒有辦法改變特定單元格只使用整數索引?

回答

2

使用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.

你的情況:

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 

編輯.ix現已正式棄用(因爲0.20.0,見here

您可以使用.loc並使用df.columns[i]來代替,例如。相當於上面是:

df.loc[df.iloc[:,0]>1,df.columns[1]] = 10 
+0

一致認爲'ix'會自行消失。 – piRSquared

0

通過用布爾掩碼切片np.arange(len(df))產生位置索引。

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

enter image description here