在dataframe添加1行(首行,或者尾部),且不覆盖

如果直接用下面的代码添加第1行,则会覆盖掉原来的第1行。

#指定位置增加一行:
df.loc[0]={
          
   a:1,b:2}
#指定位置增加一行: df.loc[0]={ a:1,b:2}

正确方法:

新建一个同样的 dataframe, 然后合并两个dataframe。

#新建一个df
df2 = pd.DataFrame([999999,空,5]).T
# 修改df2的column和df的一致
df2.columns = df.columns
# 把两个dataframe合并,需要设置 ignore_index=True
df = pd.concat([df2,df], axis=0 ,ignore_index=True) #参数axis=0表示上下合并,1表示左右合并,ignore_index=True表示忽略原来的索引 #如果在表后增加一行,则只需交换2个df的顺序:
df = pd.concat([df,df2], axis=0 ,ignore_index=True)
#新建一个df df2 = pd.DataFrame([999999,空,5]).T # 修改df2的column和df的一致 df2.columns = df.columns # 把两个dataframe合并,需要设置 ignore_index=True df = pd.concat([df2,df], axis=0 ,ignore_index=True) #参数axis=0表示上下合并,1表示左右合并,ignore_index=True表示忽略原来的索引 #如果在表后增加一行,则只需交换2个df的顺序: df = pd.concat([df,df2], axis=0 ,ignore_index=True)
如果直接用下面的代码添加第1行,则会覆盖掉原来的第1行。 #指定位置增加一行: df.loc[0]={ a:1,b:2} 正确方法: 新建一个同样的 dataframe, 然后合并两个dataframe。 #新建一个df df2 = pd.DataFrame([999999,空,5]).T # 修改df2的column和df的一致 df2.columns = df.columns # 把两个dataframe合并,需要设置 ignore_index=True df = pd.concat([df2,df], axis=0 ,ignore_index=True) #参数axis=0表示上下合并,1表示左右合并,ignore_index=True表示忽略原来的索引 #如果在表后增加一行,则只需交换2个df的顺序: df = pd.concat([df,df2], axis=0 ,ignore_index=True)
经验分享 程序员 微信小程序 职场和发展