Pandas 如何改变DataFrame列的顺序

Pandas 如何改变DataFrame列的顺序

在本文中,我们将介绍如何使用pandas中的方法来改变DataFrame列的顺序。

阅读更多:Pandas 教程

使用reindex方法

使用reindex方法可以重新排列一组数据,比如数据表中的列或限定索引。

import pandas as pd

# 创建一个DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': ['a', 'b', 'c'],
    'C': [4.1, 2.2, 3.5]
})

# 将列顺序更改为'C', 'A', 'B'
df.reindex(columns=['C', 'A', 'B'])

# 输出结果
#      C    A  B
# 0  4.1  1  a
# 1  2.2  2  b
# 2  3.5  3  c

使用loc方法

使用loc方法可以轻松地选择和重新排列列。通过选择以新的顺序排列列,可以创建具有新顺序的DataFrame。

import pandas as pd

# 创建一个DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': ['a', 'b', 'c'],
    'C': [4.1, 2.2, 3.5]
})

# 将列顺序更改为'C', 'A', 'B'
df.loc[:, ['C', 'A', 'B']]

# 输出结果
#      C    A  B
# 0  4.1  1  a
# 1  2.2  2  b
# 2  3.5  3  c

使用iloc方法

使用iloc方法可以按顺序选择列并重新排列它们。

import pandas as pd

# 创建一个DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': ['a', 'b', 'c'],
    'C': [4.1, 2.2, 3.5]
})

# 将列顺序更改为'C', 'A', 'B'
df = df.iloc[:, [2, 0, 1]]

# 输出结果
#      C    A  B
# 0  4.1  1  a
# 1  2.2  2  b
# 2  3.5  3  c

使用drop和insert方法

使用drop方法删除不需要的列,然后使用insert方法按照指定顺序插入列。

import pandas as pd

# 创建一个DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': ['a', 'b', 'c'],
    'C': [4.1, 2.2, 3.5]
})

# 将列顺序更改为'C', 'A', 'B'
df = df.drop(['A'], axis=1)
df.insert(0, 'A', [1, 2, 3])

# 输出结果
#      A    C  B
# 0  1  4.1  a
# 1  2  2.2  b
# 2  3  3.5  c

总结

在pandas中改变DataFrame列的顺序有很多种方法,包括使用reindex、loc、iloc、drop和insert方法。使用这些方法之一,可以方便地重新排列列。选择最适合您的数据和操作的方法。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程