我要使用邏輯索引來修改Pandas DataFrame(版本0.15.2)中的值,如本post所述.我一直收到以下警告:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the the caveats in the documentation: http://pandas./pandas-docs/stable/indexing.html#indexing-view-versus-copy
self.obj[item_labels[indexer[info_axis]]] = value
這是一個示例進行演示.
import pandas as pd
import numpy as np
df = pd.DataFrame({'A':[9,10]*6,
'B':range(23,35),
'C':range(-6,6)})
print df
A B C
0 9 23 -6
1 10 24 -5
2 9 25 -4
3 10 26 -3
4 9 27 -2
5 10 28 -1
6 9 29 0
7 10 30 1
8 9 31 2
9 10 32 3
10 9 33 4
11 10 34 5
使用邏輯索引更改值的正確方法是什么?假設(shè)我要從B列中所有> 30,為什么不首選以下內(nèi)容?我意識到這是鏈?zhǔn)阶鳂I(yè),不鼓勵使用.在我實際上使用的代碼中,它確實完成了我想要的操作(它不是進行復(fù)制,而是實際上在編輯原始DataFrame),但仍顯示警告:
df['B-type'] = 'B' # create column with dummy values
df['B-type'][df['B'] > 30] = 'BI' # populate the column with real values for BI type
df['B-type'][df['B'] <= 30] = 'BII' # populate the column with real values for BII type
print df
A B C B-type
0 9 23 -6 BII
1 10 24 -5 BII
2 9 25 -4 BII
3 10 26 -3 BII
4 9 27 -2 BII
5 10 28 -1 BII
6 9 29 0 BII
7 10 30 1 BII
8 9 31 2 BI
9 10 32 3 BI
10 9 33 4 BI
11 10 34 5 BI
目前尚不清楚為什么這是“錯誤的”,但仍然可以正常工作. 解決方法: 一種方法是使用如下所示的.loc –
df.loc[df['B'] > 30,'B'] = df.loc[df['B'] > 30,'B'] - 10
演示-
In [9]: df = pd.DataFrame({'A':[9,10]*6,
...: 'B':range(23,35),
...: 'C':range(-6,6)})
In [10]:
In [10]: df
Out[10]:
A B C
0 9 23 -6
1 10 24 -5
2 9 25 -4
3 10 26 -3
4 9 27 -2
5 10 28 -1
6 9 29 0
7 10 30 1
8 9 31 2
9 10 32 3
10 9 33 4
11 10 34 5
In [11]: df.loc[df['B'] > 30,'B'] = df.loc[df['B'] > 30,'B'] - 10
In [12]: df
Out[12]:
A B C
0 9 23 -6
1 10 24 -5
2 9 25 -4
3 10 26 -3
4 9 27 -2
5 10 28 -1
6 9 29 0
7 10 30 1
8 9 21 2
9 10 22 3
10 9 23 4
11 10 24 5
或者,如評論中所述,您還可以使用上述擴展作業(yè)版本-
df.loc[df['B'] > 30,'B'] -= 10
來源:https://www./content-1-528351.html
|