【问题标题】:how to use lists as values in pandas dataframe?如何在熊猫数据框中使用列表作为值?
【发布时间】:2015-01-04 12:41:23
【问题描述】:

我有一个数据框,它需要列的子集才能包含具有多个值的条目。下面是一个带有“runtimes”列的数据框,其中包含程序在各种条件下的运行时间:

df = [{"condition": "a", "runtimes": [1,1.5,2]}, {"condition": "b", "runtimes": [0.5,0.75,1]}]
df = pandas.DataFrame(df)

这构成了一个数据框:

  condition        runtimes
0         a     [1, 1.5, 2]
1         b  [0.5, 0.75, 1]

如何使用此数据框并让 pandas 将其值视为数字列表?例如计算跨行的“运行时”列的平均值?

df["runtimes"].mean()

给出错误:"Could not convert [1, 1.5, 2, 0.5, 0.75, 1] to numeric"

使用此数据帧并将它们序列化为 csv 文件会很有用,其中类似的列表:[1, 1.5, 2] 被转换为 "1,1.5,2",因此它仍然是 csv 文件中的单个条目。

【问题讨论】:

    标签: python csv numpy pandas dataframe


    【解决方案1】:

    感觉就像您在尝试让 Pandas 成为它不是的东西。如果您总是有 3 个运行时,则可以创建 3 个列。然而,更多的 Pandas-esqe 方法是将您的数据(无论您有多少不同的试验)标准化为如下所示:

    df = [{"condition": "a", "trial": 1, "runtime": 1},
          {"condition": "a", "trial": 2, "runtime": 1.5},
          {"condition": "a", "trial": 3, "runtime": 2},
          {"condition": "b", "trial": 1, "runtime": .5},
          {"condition": "b", "trial": 2, "runtime": .75},
          {"condition": "b", "trial": 3, "runtime": 1}]
    df = pd.DataFrame(df)
    

    那么你就可以了

    print df.groupby('condition').mean()
    
    
               runtime  trial
    condition                
    a             1.50      2
    b             0.75      2
    

    这里的概念是保持数据表格形式,每个单元格只有一个值。如果你想做嵌套列表函数,那么你应该使用列表,而不是 Pandas 数据框。

    【讨论】:

      【解决方案2】:

      看起来 pandas 正在尝试将系列中的所有列表相加并除以行数。这会导致列表串联,并且结果无法通过数字类型检查。这解释了您的错误中的列表。

      你可以这样计算平均值:

      df['runtimes'].apply(numpy.mean)
      

      除此之外,pandas 不喜欢将列表用作值。如果您的数据是表格的,请考虑将列表分成三个单独的列。

      序列化列将以类似的方式工作:

      df['runtimes'].apply(lambda x: '"' + str(x)[1:-1] + '"')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-11
        • 2021-12-20
        • 1970-01-01
        • 2023-03-14
        • 2018-01-07
        • 2017-07-15
        相关资源
        最近更新 更多