Python 将行的修改副本添加到数据框中
假设下面有一个数据框Python 将行的修改副本添加到数据框中,python,python-3.x,dataframe,indexing,append,Python,Python 3.x,Dataframe,Indexing,Append,假设下面有一个数据框 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 =
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
换句话说,假设我想先添加行,然后再修改它,我如何才能获得添加行的索引?正如我所看到的,您修改了当前df行的每个值,因此可能不需要复制当前行并获得警告 只需使用您的值创建一个
dict
,并将其附加到df
:
newrow = {'A':99,'B':90,'C':92, 'D':93}
df = df.append(newrow, ignore_index=True)
使用
ignore\u index=True
和newrow
将只是df中的最后一个索引。如果没有使用ignore\u index=True
提示,请使用df.iloc[-1]
查找附加行。更精确一些:我不希望从头开始创建。这就是我抄袭的原因。想象一下30列,我需要修改2到3列。谢谢你的修改。实际上,我刚刚运行了您提供的确切代码,但没有显示SettingWithCopyWarning错误。我使用的是Pandas 0.21.0和Python3.5.2。我同意,我似乎无法在这个示例中重现错误。进程链正在从序列化数据帧读取数据,复制一行并修改它。我不确定链条的哪一部分会引发这个问题。如果我们发现警告出现的真实场景,我们将再次提出警告。谢谢
newrow = {'A':99,'B':90,'C':92, 'D':93}
df = df.append(newrow, ignore_index=True)