首页 > 解决方案 > 熊猫适用于以列表为值的数据框

问题描述

我有一个包含两列的数据框,列A是整数列表,列B包含整数。我想要的输出是一个熊猫系列,它的值是列表,通过将列表中的每个元素乘以列中A的相应元素获得B

我试图使用apply,但我有意外的行为。

设置 1: 如果列表中的最大长度A 恰好等于 DataFrame 的列数,我会得到一个具有原始形状的 DataFrame,而不是 TimeSeries

ts1 = pd.Series([[1, 2], [3], [4, 5]])
ts2 = pd.Series([1, 2, 3])

df = pd.concat([ts1, ts2], keys=['A', 'B'], axis=1)

def foo(x):
    return [el * x['B'] for el in x['A']]

df.apply(foo, axis=1)

    A   B
0   1   2
1   6   6
2  12  15

设置 2: 对于列表的任意长度A(这是我的用例),apply失败:

ts1 = pd.Series([[1, 2], [3], [4, 5, 6]])
ts2 = pd.Series([1, 2, 3])

df = pd.concat([ts1, ts2], keys=['A', 'B'], axis=1)

def foo(x):
    return [el * x['B'] for el in x['A']]

df.apply(foo, axis=1, reduce=False)

ValueError: could not broadcast input array from shape (3) into shape (2)

我在 python 3.4 中使用 pandas 0.21.1

我试图玩弄applybroadcastreduce参数,但没有成功。

问题:

标签: pythonpandasdataframe

解决方案


您还可以将列表转换为 numpy 数组并在两个系列上使用广播

df.A.apply(np.array) * df.B
#Out:
0      [1, 2]
1         [6]
2    [12, 15]
dtype: object

推荐阅读