【发布时间】:2023-02-26 16:47:02
【问题描述】:
我想向数据框添加或附加一行(以列表的形式)。所有方法都要求我首先将列表转换为另一个数据框,例如。
df = df.append(another dataframe)
df = df.merge(another dataframe)
df = pd.concat(df, another dataframe)
如果索引在 https://www.statology.org/pandas-add-row-to-dataframe/ 的运行编号中,我发现了一个技巧
import pandas as pd
#create DataFrame
df = pd.DataFrame({'points': [10, 12, 12, 14, 13, 18],
'rebounds': [7, 7, 8, 13, 7, 4],
'assists': [11, 8, 10, 6, 6, 5]})
#view DataFrame
df
points rebounds assists
0 10 7 11
1 12 7 8
2 12 8 10
3 14 13 6
4 13 7 6
5 18 4 5
#add new row to end of DataFrame
df.loc[len(df.index)] = [20, 7, 5]
#view updated DataFrame
df
points rebounds assists
0 10 7 11
1 12 7 8
2 12 8 10
3 14 13 6
4 13 7 6
5 18 4 5
6 20 7 5
但是,数据框必须在运行编号中有索引,否则,添加/追加将覆盖现有数据。
所以我的问题是:是否有简单、万无一失的方法来将列表附加/添加到数据框?
非常感谢 !!!
【问题讨论】:
标签: pandas