如何在pandas数据帧中使用列表作为值?

5 python csv numpy dataframe pandas

我有一个数据框,要求列的子集具有多个值的条目.下面是一个带有"runtimes"列的数据框,它具有各种条件下程序的运行时:

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

这使得数据帧:

  condition        runtimes
0         a     [1, 1.5, 2]
1         b  [0.5, 0.75, 1]
Run Code Online (Sandbox Code Playgroud)

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

df["runtimes"].mean()
Run Code Online (Sandbox Code Playgroud)

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

使用这些数据帧并将它们序列化为csv文件是很有用的,其中列表如下: [1, 1.5, 2]转换成"1,1.5,2"csv文件中的单个条目.

JD *_*ong 9

感觉就像你正试图让熊猫成为它不是的东西.如果您总是有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)
Run Code Online (Sandbox Code Playgroud)

然后你可以

print df.groupby('condition').mean()


           runtime  trial
condition                
a             1.50      2
b             0.75      2
Run Code Online (Sandbox Code Playgroud)

这里的概念是保持数据表格,每个单元格只有一个值.如果您想要嵌套列表函数,那么您应该使用列表,而不是Pandas数据帧.


Mik*_*ike 6

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

您可以这样计算平均值:

df['runtimes'].apply(numpy.mean)
Run Code Online (Sandbox Code Playgroud)

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

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

df['runtimes'].apply(lambda x: '"' + str(x)[1:-1] + '"')
Run Code Online (Sandbox Code Playgroud)