[英]Add modified copy of a row into Data frame
Let's say we have a data frame below假设我们在下面有一个数据框
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
I would want to append a new row from the existing data and modify several columns我想从现有数据中追加一个新行并修改几列
newrow = df.loc[0].copy()
newrow.A = 99
newrow.B = 90
df.append(newrow)
By doing this I got a warning when trying to modify the row通过这样做,我在尝试修改行时收到警告
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
What would be the clean way of achieving what I intend to do ?实现我打算做的事情的干净方式是什么? I won't have index to use loc because the row is not inside the df yet我不会有使用 loc 的索引,因为该行不在 df 内
If later I would like to come back to this row, how could I retrieve its index at the moment of appending.如果稍后我想回到这一行,我怎么能在追加时检索它的索引。
newrow = df.loc[0].copy() df.append(newrow) df.loc[which index to use, "A"] = 99
In other words, let's say I would want to add the row first then modify it later, how could I get the added row's index换句话说,假设我想先添加行然后再修改它,我怎么能得到添加行的索引
As I can see, you modify every value of the current df row, so it might unnecessary to copy the current row and get the warning.正如我所看到的,您修改了当前 df 行的每个值,因此可能没有必要复制当前行并获得警告。
Just create a dict
with your values and append it to the df
:只需使用您的值创建一个dict
并将其附加到df
:
newrow = {'A':99,'B':90,'C':92, 'D':93}
df = df.append(newrow, ignore_index=True)
Use ignore_index=True
and the newrow
will just be the last index in your df.使用ignore_index=True
并且newrow
将只是您的 df 中的最后一个索引。
如果您没有使用ignore_index = True
提示,请使用df.iloc[-1]
查找附加行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.