通过过滤数据帧分配库仑

时间:2020-05-09 15:05:41

标签: python pandas

如果country_US的值为'US',我想给特征country分配一个特定的值1。这是我尝试过的两件事,但是收到警告和X_test时也未使用country_US功能进行更新。

X_test[X_test['country']=='US].loc[:,'country_US']=1

AND

X_test.loc[X_test['country']=='US].loc[:,'country_US']=1

警告-

C:\ Users \ DELL \ Anaconda3 \ lib \ site-packages \ pandas \ core \ indexing.py:671:SettingWithCopyWarning: 试图在DataFrame的切片副本上设置一个值

请参阅文档中的警告:https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy self._setitem_with_indexer(索引器,值)

2 个答案:

答案 0 :(得分:2)

对于初学者来说,确实有多种方法可以实现:

import numpy as np
#recomended:

X_test['country_US']=np.where(X_test['country'].eq('US'), 1,0)

#less recommended, yet working:

X_test['country_US']=0
X_test.loc[X_test['country'].eq('US'), 'country_US']=[1]

答案 1 :(得分:0)

除了Grzegorz Skibinski提出的建议外,我还要提及

X_test[X_test['country']=='US].loc[:,'country_US']=1

此处似乎缺少分号。您也可以尝试

t=X_test[X_test['country']=='US'] #Returns a dataframe
t['country_US']=1

在这里,我正在使用分区,这有助于我们轻松进行过滤,因为老实说,单行代码会让我感到困惑。 希望对您有帮助

相关问题