我要使用逻辑索引来修改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 insteadSee the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy self.obj[item_labels[indexer[info_axis]]] = value
这是一个示例进行演示.
import pandas as pdimport numpy as npdf = pd.DataFrame({'A':[9,10]*6, 'B':range(23,35), 'C':range(-6,6)})print df A B C0 9 23 -61 10 24 -52 9 25 -43 10 26 -34 9 27 -25 10 28 -16 9 29 07 10 30 18 9 31 29 10 32 310 9 33 411 10 34 5
使用逻辑索引更改值的正确方法是什么?假设我要从B列中所有> 30,为什么不首选以下内容?我意识到这是链式作业,不鼓励使用.在我实际上使用的代码中,它确实完成了我想要的操作(它不是进行复制,而是实际上在编辑原始DataFrame),但仍显示警告:
df['B-type'] = 'B' # create column with dummy valuesdf['B-type'][df['B'] > 30] = 'BI' # populate the column with real values for BI typedf['B-type'][df['B'] <= 30] = 'BII' # populate the column with real values for BII typeprint df A B C B-type0 9 23 -6 BII1 10 24 -5 BII2 9 25 -4 BII3 10 26 -3 BII4 9 27 -2 BII5 10 28 -1 BII6 9 29 0 BII7 10 30 1 BII8 9 31 2 BI9 10 32 3 BI10 9 33 4 BI11 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]: dfOut[10]: A B C0 9 23 -61 10 24 -52 9 25 -43 10 26 -34 9 27 -25 10 28 -16 9 29 07 10 30 18 9 31 29 10 32 310 9 33 411 10 34 5In [11]: df.loc[df['B'] > 30,'B'] = df.loc[df['B'] > 30,'B'] - 10In [12]: dfOut[12]: A B C0 9 23 -61 10 24 -52 9 25 -43 10 26 -34 9 27 -25 10 28 -16 9 29 07 10 30 18 9 21 29 10 22 310 9 23 411 10 24 5
或者,如评论中所述,您还可以使用上述扩展作业版本-
df.loc[df['B'] > 30,'B'] -= 10
来源:https://www.icode9.com/content-1-528351.html
联系客服