【问题标题】:How to concatenate a list of unknown length of data frames with another data frame in pandas?如何将未知长度的数据帧列表与熊猫中的另一个数据帧连接起来?
【发布时间】:2019-05-16 08:35:43
【问题描述】:

我正在尝试使用 pandas concatenate 将数据帧列表与另一个数据帧连接起来,以用于张量流的训练功能。该列表包含未知数量的数据帧。

import pandas as pd

res_train_x = [a, b, c, d, e....]
# here each variable is a data frame. Ex: a = [], b = [], c = [] and so on
res_train_y  = aa

# this is how I need the code to work
result = pd.concat([a, b, c, d, e, ..., aa], axis=0)

# my existing code
result = pd.concat([res_train_x, res_train_y], axis=0)

我在运行现有代码时收到此错误。

TypeError:无法连接类型为“”的对象;只要 pd.Series、pd.DataFrame 和 pd.Panel(已弃用)obj 有效

在与res_train_y 连接之前,我需要将列表res_train_x 分开。

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    正如错误消息所提到的,列表必须是 pd.Series 类型,至少要使串联工作。为此,您只需在列表上应用pd.Series,然后您就可以连接。这是一个例子

    import pandas as pd 
    # given two lists a and b
    a = [1, 2, 3]
    b = [4, 5, 6]
    # if you try to concatenate them with converting to pd.Series
    pd.concat([a, b], axis=0)
    # You will get a type error:
    # TypeError: cannot concatenate object of type "<type 'list'>"; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid
    
    # if you convert to pd.Series before concatenate, it works:
    pd.concat([pd.Series(a), pd.Series(b)], axis=0)
    

    示例输出为:

    Out[5]: 
    0    1
    1    2
    2    3
    0    4
    1    5
    2    6
    dtype: int64
    

    修复您的示例的整体代码:

    import pandas as pd 
    res_train_x = [1, 2, 3]
    res_train_y = [4, 5, 6]
    result = pd.concat([pd.Series(res_train_x), pd.Series(res_train_y)], axis=0)
    

    更新问题的答案:

    如果res_train_xres_train_y 都是数据框列表,则需要将列表连接起来,然后再连接数据框,如下所示:

    all_dfs = res_train_x + res_train_y
    result = pd.concat(all_dfs, axis=0)
    

    【讨论】:

    • 感谢您的回复!我对我的问题进行了一些编辑。请您再检查一次好吗?我需要在连接之前将res_train_x 分开。
    • @Black_Pulse 也是 pd.dataframe 还是 pd.Series?
    • res_train_xres_train_y 都包含 pd.dataframes。我想知道是否可以传递用于连接它们的数据帧,因为如果它是 pd.Series 或 pd.dataframe,我还有另一个函数来处理 result
    【解决方案2】:

    如果我正确理解您的问题,您希望将列表res_train_x 中的每个数据框连接到数据框aa

    你可以把它放在一个循环中:

    for i in range(len(res_train_x)):
        new_df = pd.concat([res_train_x[i], res_train_y],axis=0)
    

    【讨论】:

    • 谢谢!我有一个问题,我是否只需要传递系列或者数据帧是否足以使用连接?
    • 我只用数据框测试了它,它按预期工作。
    猜你喜欢
    • 2020-05-12
    • 2017-04-06
    • 2018-12-25
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 2016-08-18
    相关资源
    最近更新 更多