如何从删除的表中取回列(序列)?

2024-06-10 10:42:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

How to get back the dropped column from the table. I tried to get back the column with reset_drop() but it doesn't work.

The final outcome should look like this:

 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

Tags: thetodfgetnamesdropprintchemistry
2条回答

拥有一个主数据帧,然后在其中执行操作总是一个好的做法 我建议保持最佳命名实践,并给出子集数据帧有意义的名称。你知道吗

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

使用^{}提取列到Series,使用^{}添加到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

如果列不是最后一个,则按原始列添加^{}

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

相关问题 更多 >