【问题标题】:Add modified copy of a row into Data frame将行的修改副本添加到数据框中
【发布时间】:2018-05-11 20:22:16
【问题描述】:

假设我们下面有一个数据框

df = pd.DataFrame(numpy.random.randint(0,5,size=(5, 4)), columns=list('ABCD'))
df
   A  B  C  D
0  3  3  0  0
1  0  3  3  2
2  1  0  0  0
3  2  4  4  0
4  3  2  2  4

我想从现有数据中追加一个新行并修改几列

newrow = df.loc[0].copy()
newrow.A = 99
newrow.B = 90
df.append(newrow)

通过这样做,我在尝试修改行时收到警告

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
<string>:23: 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
  1. 实现我打算做的事情的干净方法是什么?我没有使用 loc 的索引,因为该行还没有在 df 中

  2. 如果以后我想回到这一行,我怎么能在追加的时候检索它的索引。

newrow = df.loc[0].copy()
df.append(newrow)
df.loc[which index to use, "A"] = 99

换句话说,假设我想先添加行,然后再修改它,我怎么能得到添加行的索引

【问题讨论】:

    标签: python python-3.x dataframe indexing append


    【解决方案1】:

    正如我所见,您修改了当前 df 行的每个值,因此可能不需要复制当前行并收到警告。

    只需使用您的值创建一个dict 并将其附加到df

    newrow = {'A':99,'B':90,'C':92, 'D':93}
    df = df.append(newrow, ignore_index=True)
    

    使用ignore_index=Truenewrow 将是您的 df 中的最后一个索引。

    【讨论】:

    • 更精确一些:我不希望从头开始创建。这就是我复制的原因。想象一下 30 列,我需要修改 2 或 3 列。
    • 感谢您的修改。实际上,我刚刚运行了您提供的确切代码,但未出现 SettingWithCopyWarning 错误。我正在使用 Pandas 0.21.0 和 Python 3.5.2。
    • 我同意,我似乎无法用这个例子重现错误。进程链正在从序列化数据帧中读取,复制 1 行并对其进行修改。我不确定链条的哪一部分引发了这个问题。如果我们发现警告出现的真实场景,我们将再次提出它。谢谢
    【解决方案2】:

    如果您没有使用ignore_index = True 提示,请使用df.iloc[-1] 查找附加行。

    【讨论】:

      猜你喜欢
      • 2018-10-23
      • 2011-10-17
      • 1970-01-01
      • 2016-09-23
      • 2016-08-24
      相关资源
      最近更新 更多