【问题标题】:Pandas >0.20 indexing with labels and position for a writing operation带有标签和位置的 Pandas >0.20 索引以进行写入操作
【发布时间】:2018-12-31 22:08:15
【问题描述】:

由于 ix 运算符自 0.20 版本起已弃用,我应该如何更新此行?

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

我试过了:

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

并且适用于读取操作(由于双索引而不是最有效的......但有效)。但是为了写作

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

我明白了

SettingWithCopyWarning:试图在一个副本上设置一个值 从 DataFrame 切片请参阅文档中的注意事项: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

!/usr/bin/env python3

我以某种方式克服了这个限制:

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

在我看来,这是一种解决方法。有没有更好的办法?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用Index.get_loc 作为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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-12
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多