pandas 使用 for 循环的数据帧连接不起作用

pandas dataframe concat using for loop not working

我在这里尝试使用 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')

您使用 Python 名称到对象的映射不同于它们的工作方式(您可能会对其他语言的引用感到困惑)。

当你使用

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

则右边的df表示"the object mapped to by the name df"(即AB)。左边的 df 就是 name 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)