gpt4 book ai didi

python - df.append() 没有 append 到 DataFrame

转载 作者:太空宇宙 更新时间:2023-11-03 12:53:12 25 4
gpt4 key购买 nike

我制定了this question关于添加带索引的行,但我还不清楚在没有索引时如何/为什么会发生这种情况:

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)

我希望这里有一个 2X4 的数据框。尽管如此,没有添加任何值,也没有发生错误。

print(df8.shape)
#>>> (0,4)

为什么没有添加系列,为什么没有报错?


如果我尝试添加带有 LOC 的行,则会添加一个索引,

df8.loc[df8.index.max() + 1, :] = [4, 5, 6,7]
print(df8)

结果:

     A  B  C  D
NaN 4 5 6 7

我猜LOC和iLOC都不能用于追加没有索引名的行(即loc添加索引名NaN,当索引号高于数据库的行时iLoc不能使用)

最佳答案

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.

您需要将结果分配回来。

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

关于python - df.append() 没有 append 到 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53924656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com