将列表作为带索引的新行追加到pandas数据框

2024-09-29 00:17:20 发布

您现在位置:Python中文网/ 问答频道 /正文

尽管在将数据附加到数据帧时有许多堆栈溢出问题,但我还是找不到以下问题的答案。 我正在寻找一个直接的解决方案来附加一个列表作为数据帧的最后一行。 假设我有一个简单的数据帧:

 indexlist=['one']
 columnList=list('ABC')
 values=np.array([1,2,3])
 # take care, the values array is a 3x1 size array. 
 # row has to be 1x3 so we have to reshape it

values=values.reshape(1,3)
df3=pd.DataFrame(values,index=indexlist,columns=columnList)
print(df3)

     A  B  C
one  1  2  3

经过一些操作后,我得到以下列表:

listtwo=[4,5,6]

我想把它附加在数据帧的末尾。 我把名单改成一系列:

oseries=pd.Series(listtwo)
print(type(oseries))
oseries.name="two"

现在,这不起作用:

df3.append(oseries)

因为它提供了:

A   B   C   0   1   2
one 1.0 2.0 3.0 NaN NaN NaN
two NaN NaN NaN 5.0 6.0 7.0

我想要B和C下的值

我也试过:

df3.append(oseries, columns=list('ABC'))  *** not working ***
df3.append(oseries, ignore_index=True)  *** working but wrong result
df3.append(oseries, ignore_index=False) *** working but wrong result

df3.loc[oseries.name]=oseries adds a row with NaN values

我要找的是 a) 如何将列表添加到特定索引名 b) 如何简单地从列表中添加一行值,即使我没有索引的名称(保留为空)


Tags: 数据列表indexnanarrayonelistworking
1条回答
网友
1楼 · 发布于 2024-09-29 00:17:20

使用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

或者,使用df.append,第二个参数是具有适当索引和名称的Series对象:

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

如果要附加到没有索引的数据帧(即具有数字索引),则可以在找到索引的最大值并递增1之后使用loc

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

或者,将appendignore_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

相关问题 更多 >