Creating new Dataframe data slicing issue

让人想犯罪 __ 提交于 2020-01-30 08:44:04

问题


This is my code snippet. The code works however, I am getting the following error:

"A value is trying to be set on a copy of a slice from a DataFrame"

I am guessing this is due to some deprecated syntax...

new_data['mon_fri'] = 0
for i in range(0,len(new_data)):
    if (new_data['Dayofweek'][i] == 0 or new_data['Dayofweek'][i] == 4):
        new_data['mon_fri'][i] = 1
    else:
        new_data['mon_fri'][i] = 0

回答1:


Dont loop in pandas if exist vectorized alternatives, here is possible use isin for boolean mask and cast to integer for True/False to 1/0 mapping:

new_data['mon_fri'] = new_data['Dayofweek'].isin([0,4]).astype(int)

Or use numpy.where:

new_data['mon_fri'] = np.where(new_data['Dayofweek'].isin([0,4]), 1, 0)


来源:https://stackoverflow.com/questions/54842044/creating-new-dataframe-data-slicing-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!