【问题标题】:"A value is trying to be set on a copy of a slice from a DataFrame" even when .loc is used“试图在来自 DataFrame 的切片副本上设置一个值”,即使使用 .loc 也是如此
【发布时间】:2016-11-03 03:09:45
【问题描述】:

如果我使用 .loc 创建 another_df 数据框,我不明白为什么会发生这种情况

>>> df = DataFrame({'a':range(0,10), 'b':range(10,20), 'c':range(20,30)}, index = range(0,10), columns=['a', 'b', 'c'])
>>> df
   a   b   c
0  0  10  20
1  1  11  21
2  2  12  22
3  3  13  23
4  4  14  24
5  5  15  25
6  6  16  26
7  7  17  27
8  8  18  28
9  9  19  29
>>> another_df =  df.loc[(df.a>4)&(df.b>14)&(df.c>24),:]
>>> another_df
   a   b   c
5  5  15  25
6  6  16  26
7  7  17  27
8  8  18  28
9  9  19  29
>>> another_df['d'] = 'a random string'
<string>:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

【问题讨论】:

    标签: python python-2.7 pandas indexing dataframe


    【解决方案1】:
    df.loc[(df.a>4)&(df.b>14)&(df.c>24),:]
    

    正在返回df的视图或副本

    使用copy:

    df = DataFrame({'a':range(0,10), 'b':range(10,20), 'c':range(20,30)},
                   index = range(0,10), columns=['a', 'b', 'c'])
    another_df =  df.loc[(df.a>4)&(df.b>14)&(df.c>24),:].copy()
    #                                                    ^
    #                                                   here
    another_df['d'] = 'a random string'
    

    【讨论】:

      【解决方案2】:

      您需要指定哪一行来获取新列'd' 的值'a random string'。或者你可以给列一个长度为len(another_df)的元素列表:

      another_df['d']=['hello', 'world', 'hello', 'world', 'hello']
      

      【讨论】:

      • 不,我不知道。该语句将把这个值赋给所有行
      • 我误解了你的意图。如果将单个值分配给整行是您的目标,请遵循 piRSquared 的回答。
      猜你喜欢
      • 2021-08-09
      • 2016-12-22
      • 2016-08-24
      • 2018-03-25
      • 2023-03-11
      • 2018-06-18
      • 2021-08-01
      • 1970-01-01
      相关资源
      最近更新 更多