通过for循环进行迭代来更改多个数据框的列顺序

时间:2019-05-15 22:49:25

标签: python-3.x

我正在尝试更改包含相同列名的多个数据框的列顺序。为此,我正在尝试for循环,但是任何数据帧的列顺序都不会更改。

按照col_4,col_3,col_2,col_1的顺序有四列,我希望它们以col_1,col_2,col_4,col_3的顺序

我尝试过的代码如下。我是python的新手,所以如果我犯了一些菜鸟错误,请道歉

for df in df_1,df_2,df_3:
    df=df.reindex([col_1, col_2, col_4, col_3],axis=1)

1 个答案:

答案 0 :(得分:0)

您可以使用dataframe["col_name_1", "col_name_2", "col_name_3"]

这里有个例子:

import pandas as pd
import numpy as np

data1 = pd.DataFrame(np.random.randint(0, 10, (2, 3)),
                     columns=["A", "C", "B"])
data2 = pd.DataFrame(np.random.randint(0, 10, (2, 3)),
                     columns=["C", "B", "A"])
data3 = pd.DataFrame(np.random.randint(0, 10, (2, 3)),
                     columns=["B", "C", "A"])

print(data1)
#    A  C  B
# 0  5  1  3
# 1  8  8  9
print(data2)
#    C  B  A
# 0  3  2  0
# 1  5  4  2
print(data3)
#    B  C  A
# 0  4  6  7
# 1  4  8  4

new_columns_order = ["A", "B", "C"]

# Reorder data2 et data3 columns according to the data1 columns
list_dataframe = [data1, data2, data3]
for i, df in enumerate(list_dataframe):
    list_dataframe[i] = df[new_columns_order]

print("Data1:\n", list_dataframe[0])
#    A  B  C
# 0  7  6  8
# 1  3  0  7
print("Data2:\n", list_dataframe[1])
#    A  B  C
# 0  1  8  9
# 1  8  9  7
print("Data3:\n", list_dataframe[2])
#    A  B  C
# 0  8  9  4
# 1  3  4  9