pandas df.append() 没有附加到 DataFrame
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53924656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
df.append() is not appending to the DataFrame
提问by Berlines
I formulated this questionabout adding rows WITH index, but it is not yet clear to me how/why this happens when there are no indexes:
我制定了这个关于使用索引添加行的问题,但我还不清楚在没有索引时如何/为什么会发生这种情况:
columnsList=['A','B','C','D']
df8=pd.DataFrame(columns=columnsList)
L=['value aa','value bb','value cc','value dd']
s = pd.Series(dict(zip(df8.columns, L)))
df8.append(s,ignore_index=True)
df8.append(s,ignore_index=True)
I EXPECT HERE A 2X4 DATAFRAME. nevertheless no values where added, nor an error occurred.
我希望这里有一个 2X4 数据框。尽管如此,没有添加任何值,也没有发生错误。
print(df8.shape)
#>>> (0,4)
Why is the series not being added, and why is not given any error?
为什么没有添加系列,为什么没有给出任何错误?
If I try to add a row with LOC, an index is added,
如果我尝试使用 LOC 添加一行,则会添加一个索引,
df8.loc[df8.index.max() + 1, :] = [4, 5, 6,7]
print(df8)
result:
结果:
A B C D
NaN 4 5 6 7
I guess neither LOC, nor iLOC could be used to append rows without index name (i.e. Loc adds the index name NaN, and iLoc can not be used when the index number is higher than the rows of the database)
我猜LOC和iLOC都不能用来追加没有索引名的行(即Loc加索引名NaN,索引号高于数据库行数时不能使用iLoc)
回答by cs95
DataFrame.append
is not an in-place operation. From the docs,
DataFrame.append
不是就地操作。从文档中,
DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=None)
Append rows of other to the end of this frame, returning a new object. Columns not in this frame are added as new columns.
DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=None)
将 other 的行附加到此帧的末尾,返回一个新对象。不在此框架中的列将作为新列添加。
You need to assign the result back.
您需要将结果分配回来。
df8 = df8.append([s] * 2, ignore_index=True)
df8
A B C D
0 value aa value bb value cc value dd
1 value aa value bb value cc value dd
回答by Rohit Dugal
The statement data.append(sub_data) does not work on its own.
语句 data.append(sub_data) 本身不起作用。
But the statement data=data.append(sub_data) will work
但是语句 data=data.append(sub_data) 会起作用
Assigning it back solved the issue for me. Good tip not available elsewhere.
重新分配它为我解决了这个问题。其他地方没有的好提示。