Pandas 技巧:如何重新排序 DataFrame 列
要将三列调换顺序,可以使用 pandas 的 reindex 方法。下面是一个示例:
import pandas as pd
# 创建一个示例 DataFrame
data = {'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]}
df = pd.DataFrame(data)
# 将列顺序调整为C、A、B
df = df.reindex(columns=['C', 'A', 'B'])
print(df)
输出结果为:
C A B
0 7 1 4
1 8 2 5
2 9 3 6
在这个例子中,我们首先创建了一个包含三列(A、B、C)的 DataFrame。然后,使用 reindex 方法将列顺序调整为 C、A、B。最后,打印输出结果,显示调整后的 DataFrame。
原文地址: https://www.cveoy.top/t/topic/eFVq 著作权归作者所有。请勿转载和采集!