如何使用排列属性的熊猫来构建数据框?

时间:2018-08-03 12:43:36

标签: python pandas dataframe

我想用这样的熊猫制作一个数据框:

Id  Name    Gender  Math    Science English
1   Ram     Male    98      92      80
2   Hari    Male    30      40      23
3   Gita    Female  60      65      77
4   Sita    Female  50      45      55
5   Shyam   Male    80      88      82

我在python中这样写报价:

import pandas as pd
d = {'Id':[1,2,3,4,5], 'Name':['Ram','Hari','Gita','Sita','Shyam'],'Gender':['Male','Male','Female','Female','Male'],'Math':[98,30,60,50,80],'Science':[92,40,65,45,88],'English':[80,23,77,55,82]}
df = pd.DataFrame(data=d)
print (df)

它给了我这样的输出:

    English  Gender  Id  Math   Name  Science
0       80    Male   1    98    Ram       92
1       23    Male   2    30   Hari       40
2       77  Female   3    60   Gita       65
3       55  Female   4    50   Sita       45
4       82    Male   5    80  Shyam       88

如何删除没有属性的第一列,并按照问题中给出的方式排列属性? 我想要ID,姓名,性别,数学,科学,英语。谢谢

2 个答案:

答案 0 :(得分:0)

如果您不希望索引,则可以通过诸如Id之类的唯一列进行设置。

import pandas as pd
d = {'Id':[1,2,3,4,5], 'Name':['Ram','Hari','Gita','Sita','Shyam'],'Gender':['Male','Male','Female','Female','Male'],'Math':[98,30,60,50,80],'Science':[92,40,65,45,88],'English':[80,23,77,55,82]}
df = pd.DataFrame(data=d)
df.set_index('Id', inplace=True)
print (df)

输出:

     Name  Gender  Math  Science  English
Id                                       
1     Ram    Male    98       92       80
2    Hari    Male    30       40       23
3    Gita  Female    60       65       77
4    Sita  Female    50       45       55
5   Shyam    Male    80       88       82

答案 1 :(得分:0)

尝试直接创建DataFrame,而不要传递“ d”

df = pd.DataFrame({'Id': [1, 4, 7, 10], etc...})

然后使用set_index来固定您的ID:

df.set_index('Id')