【问题标题】:How to iteratively merge data frames in pandas?如何在熊猫中迭代合并数据框?
【发布时间】:2019-03-15 23:49:03
【问题描述】:

给定一个数据框列表,我想迭代地合并它们并返回单个数据框。输入:frames(pandas 数据框列表)和on_columns(包含要合并的列名的字符串或字符串列表)。如何使用df.merge 来完成此操作? """ 给定一个数据框列表,迭代合并它们并返回一个 单个数据框

"""HINT: Use slice on frames when iterating and merging.

Arguments:
    frames {list} -- a list of pandas DataFrames
    on_columns {string or list} -- a string or list of strings
     containing the column names on which to join

Returns:
    df -- a pandas.DataFrame containing a merged version of the 
    two provided dataframes. If frames is None or an empty list return None
"""
def merge(frames, on_columns):
     #implementation here
     df = #merged df



return df

编辑:我想也许我可以使用 df.concat 但不确定如何使用?

【问题讨论】:

  • 在每种情况下,on 列是否相同?似乎reduce 的情况为answered here
  • 类似,但我想合并on_columns中提供的所有列,而不仅仅是彼此不同的列。
  • 您能否提供minimal reproducible example 一些示例数据和您的预期输出?
  • 我编辑了它 - 希望能有所帮助。

标签: python pandas frames


【解决方案1】:
import pandas as pd

df = next(dfs)
for records in dfs:
    df = df.append(records)

# the above is equivalent to
df = pd.concat(dfs)

注意事项:

附:不要创建库已经提供的功能,乐于阅读文档并重新阅读文档,尤其是。因为熊猫文档是卷

【讨论】:

    【解决方案2】:

    这样的东西应该可以工作,

    def merge(frames, on_columns):
        #implementation here
        if not frames:
            return None
        if len(frames) == 1:
            return frames[0]
        out = frames[0]
        for df in frames[1:]:
            out = out.merge(df, on=on_columns)
        return out
    

    【讨论】:

    • 酷,你能接受这个作为答案然后通过投票吗?
    • 你可以去掉第二个 if 语句
    • @DoganAskan 我做到了,但由于我的声望还没有超过 15,所以我的支持没有公开显示。
    猜你喜欢
    • 2019-11-29
    • 2020-05-17
    • 2015-12-09
    • 2017-02-13
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    相关资源
    最近更新 更多