BGa*_*BGa 0 python indexing dataframe pandas
假设我们有一个简单的 pandas 数据框:
df = pd.DataFrame({"A": [1,2,3], "B": [4,5,6]})
Run Code Online (Sandbox Code Playgroud)
我想向该数据框添加一个新行。为什么下面的方法不起作用?
df.iloc[len(df)]=[9,9]
Run Code Online (Sandbox Code Playgroud)
有趣的是,如果我们使用它,它一切正常.loc[],即使len(df)是一个整数并且.iloc[]用于基于整数位置的索引,这与.loc[].
您正在使用索引分配,这不是loc来自iloc 文档。如果请求的索引器超出范围,iloc 将引发 IndexError
df.loc[len(df)]=[9,9]
df
Out[349]:
A B
0 1 4
1 2 5
2 3 6
3 9 9
Run Code Online (Sandbox Code Playgroud)