问题
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