【问题标题】:Tuple of tuples not allowed in pandas.DataFrame constructorpandas.DataFrame 构造函数中不允许元组的元组
【发布时间】:2019-06-26 14:35:05
【问题描述】:

在 python3 中使用 pandas 数据框,我尝试在元组的元组上调用数据框构造函数。它导致了不正确的构造函数调用错误。对 pandas.DataFrame 文档的快速参考显示,数据参数可以使用 numpy ndarray(结构化或同构)、dict 或 DataFrame 进行初始化,Dict 可以包含 Series、数组、常量或类似列表的对象。 我无法估计元组的元组无效和元组列表有效的原因。

我将元组的元组转换为元组的列表,它救了我的命。

batch_computer_science = ('r1', 'r2', 'r3', 'r4') #roll number of students
batch_mechanical_engg = ('a1', 'a2', 'a3', 'a4') #roll number of students
session_2018 = (batch_computer_science, batch_mechanical_engg)

#In the actual code there are 8 types of batches with 30 students each, sorted in order of registration in the class.`

session_df = pd.DataFrame(session_2018) # This throws an error, improper constructor called.

我希望元组的元组起作用,但元组列表起作用,元组的元组不起作用。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    你是对的。元组列表起作用,元组的元组不起作用。

    从 v0.23.4 开始,pd.DataFrame 类的 the source 表示 list 被视为特殊情况:

    elif isinstance(data, (list, types.GeneratorType)):
        if isinstance(data, types.GeneratorType):
            data = list(data)
        if len(data) > 0:
            if is_list_like(data[0]) and getattr(data[0], 'ndim', 1) == 1:
               # ....
    

    所以只需使用元组列表:

    session_df = pd.DataFrame(list(session_2018))
    

    请记住,Pandas 是一种 API,而不是一种编程语言。此处的详细信息如有更改,恕不另行通知。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      相关资源
      最近更新 更多