如何在 Pandas DataFrame 中移动一列?
我们可以使用shift()Pandas中的方法来移动DataFrame的列,而无需重写整个DataFrame。shift()采用以下参数
shift(self, periods=1, freq=None, axis=0, fill_value=None)
period要转移的周期 数。它也可以取负数。
axis 取一个布尔值;0如果你想移动索引和1如果你想移动列
fill_value 它将替换缺失的值。
让我们举个例子,看看如何使用这个shift()方法。
步骤
创建二维、大小可变、潜在异构的表格数据df。
打印输入数据帧,df。
选择一列并使用df["column_name]=df.column_移动它name.shift()
打印更新的DataFrame。
示例
import pandas as pd df = pd.DataFrame( dict( name=['John', 'Jacob', 'Tom', 'Tim', 'Ally'], marks=[89, 23, 100, 56, 90], subjects=["Math", "Physics", "Chemistry", "Biology", "English"] ) ) print "Input DataFrame is:\n", df df["name"] = df.name.shift(1) print "After shifting column name by 1:\n", df df["marks"] = df.marks.shift(2) print "After shifting column marks by 2:\n", df df["subjects"] = df.subjects.shift(-1) print "After shifting column subjects by -1:\n", df输出结果
Input DataFrame is: name marks subjects 0 John 89 Math 1 Jacob 23 Physics 2 Tom 100 Chemistry 3 Tim 56 Biology 4 Ally 90 English After shifting column name by 1: name marks subjects 0 NaN 89 Math 1 John 23 Physics 2 Jacob 100 Chemistry 3 Tom 56 Biology 4 Tim 90 English After shifting column marks by 2: name marks subjects 0 NaN 100 Math 1 John 100 Physics 2 Jacob 89 Chemistry 3 Tom 23 Biology 4 Tim 100 English After shifting column subjects by -1: name marks subjects 0 NaN 100 Physics 1 John 100 Chemistry 2 Jacob 89 Biology 3 Tom 23 English 4 Tim 100 NaN