Append list to pandas DataFrame as new row with index

孤街醉人 提交于 2019-12-06 07:20:54

Either assign in-place with loc:

df.loc['two'] = [4, 5, 6]
# df.loc['two', :] = [4, 5, 6]
df
     A  B  C
one  1  2  3
two  4  5  6

Or, use df.append with the second argument being a Series object having appropriate index and name:

s = pd.Series(dict(zip(df.columns, [4, 5, 6])).rename('two'))
df2 = df.append(s)

df2
     A  B  C
one  1  2  3
two  4  5  6

If you are appending to a DataFrame without an index (i.e., having a numeric index), you can use loc after finding the max of the index and incrementing by 1:

df4 = pd.DataFrame(np.array([1,2,3]).reshape(1,3), columns=list('ABC'))
df4

   A  B  C
0  1  2  3

df4.loc[df4.index.max() + 1, :] = [4, 5, 6]
df4
     A    B    C
0  1.0  2.0  3.0
1  4.0  5.0  6.0

Or, using append with ignore_index=True:

df4.append(pd.Series(dict(zip(df4.columns, [4, 5, 6]))), ignore_index=True)

   A  B  C
0  1  2  3
1  4  5  6
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!