如何从删除的表中获取列(系列)?

时间:2019-01-21 07:11:30

标签: python pandas

print(df)

    Names   Maths  Physics  Chemistry
0   Khaja    75       91    84
1   Srihari  81       89    71
2   Krishna  69       77    76
3   jain     87       69    68
4   shakir   79       70    74

df.drop(['Chemistry'],axis=1,inplace=True)

df

    Names   Maths   Physics
0   Khaja     75      91
1   Srihari   81      89
2   Krishna   69      77
3   jain      87      69
4   shakir    79      70
  

如何从表中取回被删除的列。我试图回去   带有reset_drop()的列,但是它不起作用。

     

最终结果应如下所示:

 print(df)

        Names   Maths  Physics  Chemistry
    0   Khaja    75       91    84
    1   Srihari  81       89    71
    2   Krishna  69       77    76
    3   jain     87       69    68
    4   shakir   79       70    74

2 个答案:

答案 0 :(得分:1)

使用pop将列提取到Series,用join添加到DataFrame的末尾:

a = df.pop('Chemistry')
print (a)
0    84
1    71
2    76
3    68
4    74
Name: Chemistry, dtype: int64

print (df)
     Names  Maths  Physics
0    Khaja     75       91
1  Srihari     81       89
2  Krishna     69       77
3     jain     87       69
4   shakir     79       70

df = df.join(a)
print (df)
     Names  Maths  Physics  Chemistry
0    Khaja     75       91         84
1  Srihari     81       89         71
2  Krishna     69       77         76
3     jain     87       69         68
4   shakir     79       70         74

如果该列不是最后一个列,请在原始列中添加reindex

cols = df.columns
a = df.pop('Maths')
print (a)
0    75
1    81
2    69
3    87
4    79
Name: Maths, dtype: int64

print (df)
     Names  Physics  Chemistry
0    Khaja       91         84
1  Srihari       89         71
2  Krishna       77         76
3     jain       69         68
4   shakir       70         74

df = df.join(a).reindex(columns=cols)
print (df)
     Names  Maths  Physics  Chemistry
0    Khaja     75       91         84
1  Srihari     81       89         71
2  Krishna     69       77         76
3     jain     87       69         68
4   shakir     79       70         74

答案 1 :(得分:1)

拥有一个主数据框然后在其中执行操作始终是一个好习惯 我建议保持最佳命名习惯,并给子集数据框有意义的名称。

print (Master)
     Names  Maths  Physics  Chemistry
0    Khaja     75       91         84
1  Srihari     81       89         71
2  Krishna     69       77         76
3     jain     87       69         68
4   shakir     79       70         74


Chemistry= df.pop('Chemistry')
0    84
1    71
2    76
3    68
4    74
Name: Chemistry, dtype: int64

df_withoutChemistry
     Names  Maths  Physics
0    Khaja     75       91
1  Srihari     81       89
2  Krishna     69       77
3     jain     87       69
4   shakir     79       70