【发布时间】: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
实现我打算做的事情的干净方法是什么?我没有使用 loc 的索引,因为该行还没有在 df 中
如果以后我想回到这一行,我怎么能在追加的时候检索它的索引。
newrow = df.loc[0].copy() df.append(newrow) df.loc[which index to use, "A"] = 99
换句话说,假设我想先添加行,然后再修改它,我怎么能得到添加行的索引
【问题讨论】:
标签: python python-3.x dataframe indexing append