在pandas数据框的顶部添加一行 [英] add a row at top in pandas dataframe

查看:747
本文介绍了在pandas数据框的顶部添加一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的数据框

import pandas as pd
df = pd.DataFrame({'name': ['jon','sam','jane','bob'],
           'age': [30,25,18,26],
           'sex':['male','male','female','male']})


   age  name     sex
0   30   jon    male
1   25   sam    male
2   18  jane  female
3   26   bob    male

我想在第一个位置插入新行

I want to insert a new row at the first position

姓名:院长,年龄:45,性别:男

name: dean, age: 45, sex: male

   age  name     sex
0   45  dean    male
1   30   jon    male
2   25   sam    male
3   18  jane  female
4   26   bob    male

在熊猫中做到这一点的最佳方法是什么?

What is the best way to do this in pandas?

推荐答案

如果要进行频繁操作,则从性能方面考虑,首先将数据收集到列表中,然后使用pd.concat([], ignore_index=True) (类似于 @Serenity的解决方案):

If it's going to be a frequent operation, then it makes sense (in terms of performance) to gather the data into a list first and then use pd.concat([], ignore_index=True) (similar to @Serenity's solution):

演示:

data = []

# always inserting new rows at the first position - last row will be always on top    
data.insert(0, {'name': 'dean', 'age': 45, 'sex': 'male'})
data.insert(0, {'name': 'joe', 'age': 33, 'sex': 'male'})
#...

pd.concat([pd.DataFrame(data), df], ignore_index=True)

In [56]: pd.concat([pd.DataFrame(data), df], ignore_index=True)
Out[56]:
   age  name     sex
0   33   joe    male
1   45  dean    male
2   30   jon    male
3   25   sam    male
4   18  jane  female
5   26   bob    male

PS我不会太频繁地(对于每一行)调用.append()pd.concat().sort_index(),因为它非常昂贵.因此,想法是分批进行...

PS I wouldn't call .append(), pd.concat(), .sort_index() too frequently (for each single row) as it's pretty expensive. So the idea is to do it in chunks...

这篇关于在pandas数据框的顶部添加一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆