首页 > 解决方案 > 如何从删除的表中取回列(系列)?

问题描述

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

标签: pythonpandas

解决方案


用于pop将列提取到Seriesjoin添加到末尾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

推荐阅读