pandas dataframe concat使用for循环不起作用

时间:2018-05-12 13:45:48

标签: python pandas for-loop concat

在这里,我尝试使用for循环将数据帧A和B与C连接。

data = [['Alex',10],['Bob',12],['Clarke',13]]

A = pd.Dataframe(data, columns=['Name','Age'])
B = pd.Dataframe(data, columns=['Name','Age'])
C = pd.Dataframe(data, columns=['Name','Age'])

A.columns  ---> Index(['Name', 'Age'], dtype='object')
B.columns  ---> Index(['Name', 'Age'], dtype='object')
C.columns  ---> Index(['Name', 'Age'], dtype='object')

for df in [A, B]:
    df = pd.concat([df, C], axis=1)

A.columns  ---> Index(['Name', 'Age'], dtype='object')
B.columns  ---> Index(['Name', 'Age'], dtype='object')
df.columns ---> Index(['Name', 'Age', 'Name', 'Age'], dtype='object')

为什么它不将C与原始A,B数据帧连接起来。为什么要创建新的df Dataframe?

我想要for循环:

A.columns ---> Index(['Name', 'Age', 'Name', 'Age'], dtype='object')
B.columns ---> Index(['Name', 'Age', 'Name', 'Age'], dtype='object')

1 个答案:

答案 0 :(得分:2)

你使用名称的Python映射来反对它们的工作方式(你可能会对其他语言的引用感到困惑)。

使用时

for df in [A, B]:
    df = pd.concat([df, C], axis=1)

然后右侧的df表示“通过名称df映射到的对象”(即A然后B)。左侧的df只是名称 df。因此,您的循环根本不会修改原始对象。

您可以使用

A, B = pd.concat([A, C], axis=1), pd.concat([B, C], axis=1)

如果您真的必须使用循环,则可以使用dict。首先将对象放在那里,

dfs = {'A': A, 'B': B}

然后只能通过dict

来引用它们
for k, v in dfs.items():
    dfs[k] = pd.concat([v, C], axis=1)