Led*_* Yu 26 python dataframe pandas
我正在尝试将数据帧的整个列设置为特定值.
In [1]: df
Out [1]:
issueid industry
0 001 xxx
1 002 xxx
2 003 xxx
3 004 xxx
4 005 xxx
Run Code Online (Sandbox Code Playgroud)
从我所看到的,loc是替换数据框中的值时的最佳实践(或者不是吗?):
In [2]: df.loc[:,'industry'] = 'yyy'
Run Code Online (Sandbox Code Playgroud)
但是,我仍然收到了这条备受关注的警告信息:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
Run Code Online (Sandbox Code Playgroud)
如果我做
In [3]: df['industry'] = 'yyy'
Run Code Online (Sandbox Code Playgroud)
我得到了同样的警告信息.
有任何想法吗?使用Python 3.5.2和pandas 0.18.1.
小智 18
你可以使用这个assign功能:
df = df.assign(industry='yyy')
Run Code Online (Sandbox Code Playgroud)
Ale*_*ler 13
当从现有对象定义新对象时,Python可以做出意想不到的事情.您在上面的评论中表示,您的数据框架是按照以下方式定义的df = df_all.loc[df_all['issueid']==specific_id,:].在这种情况下,df实际上只是存储在df_all对象中的行的替身:不在内存中创建新对象.
为了完全避免这些问题,我经常要提醒自己使用copy模块,该模块明确强制将对象复制到内存中,以便调用新对象的方法不会应用于源对象.我和你有同样的问题,并使用该deepcopy功能避免使用它.
在您的情况下,这应该摆脱警告消息:
from copy import deepcopy
df = deepcopy(df_all.loc[df_all['issueid']==specific_id,:])
df['industry'] = 'yyy'
Run Code Online (Sandbox Code Playgroud)
HH1*_*HH1 10
你可以做 :
df['industry'] = 'yyy'
Run Code Online (Sandbox Code Playgroud)
df.loc[:,'industry'] = 'yyy'
Run Code Online (Sandbox Code Playgroud)
这就是魔术。您将为所有行添加“ .loc”和“:”。希望能帮助到你
小智 5
对于其他寻求此答案且不想使用副本的人 -
df['industry'] = df['industry'].apply(lambda x: '')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
65737 次 |
| 最近记录: |