Pandas >0.20 indexing with labels and position for a writing operation

时间:2018-07-24 10:12:50

标签: python pandas

Since ix operator is deprecated since 0.20 version, how should I update this line?

df_final.ix[int(len(df_final)/2):, 'type'] = 1

I tried this:

df_final['type'][int(len(df_final)/2):]

and works well for reading operations (not the most efficient because of the double indexing... but works). But for writing

df_final['type'][int(len(df_final)/2):] = 0

I got

SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

!/usr/bin/env python3

I somehow overcome this limitation doing this:

target_feature_index = list(df_final.columns).index('type')
df_final.iloc[int(len(df_final)/2):, target_feature_index] = 0

It looks to me like a workaround. Is there a better way?

1 个答案:

答案 0 :(得分:0)

Use Index.get_loc for position of column type:

df_final = pd.DataFrame({
    'A': ['a','a','a','a','b','b','b'],
    'type': list(range(7))
})
print (df_final)
   A  type
0  a     0
1  a     1
2  a     2
3  a     3
4  b     4
5  b     5
6  b     6

df_final.iloc[int(len(df_final)/2):, df_final.columns.get_loc('type')] = 0
print(df_final)
   A  type
0  a     0
1  a     1
2  a     2
3  a     0
4  b     0
5  b     0
6  b     0