在pandas数据框的顶部添加一行

时间:2017-04-14 09:13:05

标签: python 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

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

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

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

在熊猫中这样做的最佳方式是什么?

6 个答案:

答案 0 :(得分:13)

如果它是一个频繁的操作,那么首先将数据收集到一个列表然后使用<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <div class="container"> <h2>To Do List</h2> <button id="btnAddProject">Add Project</button> <div id="projects"> <ul id="main"> <li><a href="#personal">Personal</a></li> <li><a href="#work">Work</a></li> </ul> <ol id="personal"> <li><input type="checkbox">Doctor appointment</li> <li><input type="checkbox">Call the plumber</li> </ol> <ol id="work"> <li><input type="checkbox">Complete test case document</li> <li><input type="checkbox">Meet project manager</li> <li><input type="checkbox">Record jQuery video</li> </ol> </div> </div> <div id="project-dialog" title="Add a project" style="display: none;"> <label for="new-project">Project name:</label><input id="new-project" type="text"> </div>(类似于@Serenity's solution是有意义的(在性能方面) ):

演示:

pd.concat([], ignore_index=True)

PS我不会太频繁地致电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 .append()pd.concat()(对于每一行),因为它非常昂贵。所以我的想法就是以大块的方式来做......

答案 1 :(得分:12)

可能这不是最有效的方式,但是:

df.loc[-1] = ['45', 'Dean', 'male']  # adding a row
df.index = df.index + 1  # shifting index
df.sort_index(inplace=True) 

输出:

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

答案 2 :(得分:3)

@edyvedy13's solution对我很有用。但是,需要针对deprecation的大熊猫进行更新。 sort方法 - 现已替换为sort_index

 df.loc[-1] = ['45', 'Dean', 'male']  # adding a row
 df.index = df.index + 1  # shifting index
 df = df.sort_index()  # sorting by index

答案 3 :(得分:1)

使用pandas.concat并重新索引新数据框:

import pandas as pd
df = pd.DataFrame({'name': ['jon','sam','jane','bob'],
           'age': [30,25,18,26],
           'sex':['male','male','female','male']})
# new line
line = pd.DataFrame({'name': 'dean', 'age': 45, 'sex': 'male'}, index=[0])
# concatenate two dataframe
df2 = pd.concat([line,df.ix[:]]).reset_index(drop=True)
print (df2)

输出:

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

答案 4 :(得分:1)

import pandas as pd


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

df1 = pd.DataFrame({'name': ['dean'], 'age': [45], 'sex':['male']})
df1 = df1.append(df)
df1 = df1.reset_index(drop=True)

有效

答案 5 :(得分:0)

这对我有用。

>>> import pandas as pd
>>> df = pd.DataFrame({'name': ['jon','sam','jane','bob'],
...            'age': [30,25,18,26],
...            'sex':['male','male','female','male']})     >>> df
   age  name     sex
0   30   jon    male
1   25   sam    male
2   18  jane  female
3   26   bob    male
>>> df.loc['a']=[45,'dean','male']
>>> df
   age  name     sex
0   30   jon    male
1   25   sam    male
2   18  jane  female
3   26   bob    male
a   45  dean    male
>>> newIndex=['a']+[ind for ind in df.index if ind!='a']
>>> df=df.reindex(index=newIndex)
>>> df
   age  name     sex
a   45  dean    male
0   30   jon    male
1   25   sam    male
2   18  jane  female
3   26   bob    male