如何更改 Panas DataFrame 列的顺序
我们将介绍如何使用 insert
和 reindex
以不同的方法更改 pandas.DataFrame
列的顺序,例如以所需的顺序分配列名。
以新顺序在对 pandas.DataFrame
列排序
最简单的方法是用 columns
的列表重新分配 DataFrame
,或者只是按照我们想要的顺序分配列名:
# python 3.x
import pandas as pd
df = pd.DataFrame(
{
"a": ["1", "2", "3", "4"],
"b": [16, 7, 6, 16],
"c": [61, 57, 16, 36],
"d": ["12", "22", "13", "44"],
"e": ["Green", "Red", "Blue", "Yellow"],
"f": [1, 11, 23, 66],
}
)
print(df)
df = df[["e", "c", "b", "f", "d", "a"]]
print("Rearranging ..................")
print("..............................")
print(df)
输出:
a b c d e f
0 1 16 61 12 Green 1
1 2 7 57 22 Red 11
2 3 6 16 13 Blue 23
3 4 16 36 44 Yellow 66
Rearranging ..................
..............................
e c b f d a
0 Green 61 16 1 12 1
1 Red 57 7 11 22 2
2 Blue 16 6 23 13 3
3 Yellow 36 16 66 44 4
在 Pandas 中用 insert
添加新列和位置
如果我们要创建新列,则可以将其插入到我们想要的任何位置:
# python 3.x
import pandas as pd
df = pd.DataFrame(
{
"a": ["1", "2", "3", "4"],
"b": [16, 7, 6, 16],
"c": [61, 57, 16, 36],
"d": ["12", "22", "13", "44"],
"e": ["Green", "Red", "Blue", "Yellow"],
"f": [1, 11, 23, 66],
}
)
print(df)
print("Inserting ..................")
print("..............................")
df.insert(0, "newColMean", df.mean(1))
print(df)
输出:
newColMean a b c d e f
0 26.000000 1 16 61 12 Green 1
1 25.000000 2 7 57 22 Red 11
2 15.000000 3 6 16 13 Blue 23
3 39.333333 4 16 36 44 Yellow 66
Pandas 中给定顺序的 reindex
列
reindex
可以说是重新排列列的最有效方法:
# python 3.x
import pandas as pd
df = pd.DataFrame(
{
"a": ["1", "2", "3", "4"],
"b": [16, 7, 6, 16],
"c": [61, 57, 16, 36],
"d": ["12", "22", "13", "44"],
"e": ["Green", "Red", "Blue", "Yellow"],
"f": [1, 11, 23, 66],
}
)
print(df)
print("Rearranging ..................")
print("..............................")
df = df.reindex(columns=["a", "f", "d", "b", "c", "e"])
print(df)
输出:
a b c d e f
0 1 16 61 12 Green 1
1 2 7 57 22 Red 11
2 3 6 16 13 Blue 23
3 4 16 36 44 Yellow 66
Rearranging ..................
..............................
a f d b c e
0 1 1 12 16 61 Green
1 2 11 22 7 57 Red
2 3 23 13 6 16 Blue
3 4 66 44 16 36 Yellow
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串