列表中的 groupby 和统计信息

groupby and stats on lists

我有一个如下所示的数据框:

'Location'    'Dir' 'Set'     'H1'    'H2'
0   Chicago     H1     4    *LIST*  *LIST*
1   Houston     H2     4    *LIST*  *LIST*
2   Los Angeles H2     4    *LIST*  *LIST*
3   Boston      H1     0    *LIST*  *LIST*
4   NYC         H2     0    *LIST*  *LIST*
5   Seattle     H1     0    *LIST*  *LIST*

所有列表项都是 NNx1 个列表。

我想要的是获得每组的平均值(又是 NNx1),这取决于 'Dir' 值。

例如,对于第 4 组,我希望他指的是芝加哥 H1、休斯顿 H2 和洛杉矶 H2。另外,我也想要平均值+/- sigma。

例如,假设:

芝加哥 H1 是 [4,8,10]

休斯顿 H2 是 [8,4,12]

洛杉矶 H2 [6,9,5]

我的意思是[6,7,9]

我认为 .groupby 方法会很有用,但我不知道如何将条件放在 'Dir' 列上,也不知道如何求列表的平均值。

有什么想法吗?

试试这个:

import pandas as pd

x = pd.DataFrame({'Location': ['Chicago','Houston','Los Angeles','Boston','NYC','Seattle'],
                  'Dir':      ['H1','H2','H2','H1','H2','H1'],
                  'Set':      [4,4,4,0,0,0],
                  'SetCopy':  [4,4,4,0,0,0]})
mean = x.groupby(['Set','Dir']).mean()
sd = x.groupby(['Set','Dir']).std()

根据评论编辑:

import pandas as pd
import numpy as np
import itertools

x = pd.DataFrame({'Location': ['Chicago','Houston','Los Angeles','Boston','NYC','Seattle'],
                  'Dir':      ['H1','H2','H2','H1','H2','H1'],
                  'Set':      [4,4,4,0,0,0],
                  'H1':       [[4,8,10],[8,4,12],[6,9,5],[6,7,9],[0,0,0],[0,0,0]]})

mean = x.groupby(['Set','Dir']).H1.apply(
    lambda x: list(x)).apply(
    lambda x: np.mean(list(itertools.chain.from_iterable(x))))

sd = x.groupby(['Set','Dir']).H1.apply(
    lambda x: list(x)).apply(
    lambda x: np.std(list(itertools.chain.from_iterable(x))))

您可以按照我在下面显示的方式获取过滤后组的逐元素平均值。一些中间步骤是必要的(重塑数据并将列表转换为 numpy 数组),但这些步骤应该产生您想要的均值列表(或数组)。

# melt H1 and H2 columns into key-value columns
# this will make it easier to select either the H1 or H2 list
df = pd.melt(df, id_vars=['Location', 'Set', 'Dir'], \
value_vars=['H1', 'H2'], var_name="Target_Dir", value_name="Values")

# convert lists to numpy arrays
# in order to be able to specify the axis for the mean calculation
df.Values = df.Values.apply(np.array)

# filter df to your target Dirs, group by Set
# and calculate element-wise means
df[df['Dir'] == df['Target_Dir']].groupby('Set')['Values'].apply(lambda x: np.mean(x, axis=0))