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
如何从表中取回已删除的列。我试图用 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
解决方案
用于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
推荐阅读
- flutter - 如何停止 ColorFiltered 混合?
- laravel-8 - Jetstream 用户配置文件更新:使用 Livewire 表单输入传递 $input[] 字段时出现问题
- javascript - 为什么这个 javascript while 循环会挂起?
- python - 将多个类分配给具有数字数据的列中的新变量
- android-studio - SharedPreference 没有保存最后添加的 stringSet
- html - Html / CSS:图像斜切屏幕的一半
- windows - 根据点距离调整图像大小
- python - 使用 .loc 从 pandas 请求数据
- html - 尝试在 Vuejs 中突出显示边框颜色时出错?
- swiftui - 表单中的 SwiftUI 选择器。选择后分隔符消失