在 Pandas 数据框中添加带有索引的空行

问题描述 投票:0回答:3

在我看到的所有示例和答案中,如果需要在 Pandas 数据框中添加空行,请全部使用:

ignore_index=True

如果我想保留当前索引,并向具有给定索引的数据帧追加一个空行,该怎么办?

python pandas indexing row
3个回答
7
投票

我们使用

reindex

df.reindex(df.index.values.tolist()+['Yourindex'])
Out[1479]: 
             A    B
0          one   Aa
1          one   Bb
2          two   Cc
Yourindex  NaN  NaN

数据输入

df = pd.DataFrame({'A' : ['one', 'one', 'two'] ,
                   'B' : ['Aa', 'Bb', 'Cc'] })

0
投票

我使用这种方法...

df = pd.DataFrame({'A' : ['one', 'one', 'two'] ,
                   'B' : ['Aa', 'Bb', 'Cc'] })
new_df = pd.concat([df, pd.DataFrame(index=pd.Index(['New Index']))])

0
投票

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) df.loc[len(df)] = pd.Series()

或将其与插入值一起使用 df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) df.loc['你的索引','A'] = 20

© www.soinside.com 2019 - 2024. All rights reserved.