【问题标题】:pandas dataframe concat using for loop not working使用for循环的熊猫数据框concat不起作用
【发布时间】:2018-10-22 17:33:08
【问题描述】:

在这里,我尝试使用 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 pandas for-loop concat


    【解决方案1】:

    您使用 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)
    

    【讨论】:

    • 同意,循环在这里可能并不理想。我要为 Ami 的回答添加两个建议:首先,您可以使用列表而不是 dict(更改为 dfs = [A,B] 和 k, v in enumerate(dfs))。其次,您也可以将其作为理解而不是 for 循环。作为列表理解,这将是 dfs = [pd.concat([x, C], axis = 1) for x in [A,B]]
    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 2015-12-24
    • 1970-01-01
    • 2015-09-19
    • 2018-08-20
    • 2022-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多