代码之家  ›  专栏  ›  技术社区  ›  FLab

熊猫应用于数据帧,列表作为值

  •  0
  • FLab  · 技术社区  · 6 年前

    我有一个数据框架,有两列,列 A 整数和列的列表 B 包含整数。 我想要的输出是一个pandas系列,其值是列表,通过将列表中的每个元素乘以 按列中的相应元素 .

    我试着用 apply 但我有意想不到的行为。

    设置1: 如果列表在 发生 为了使最大长度等于数据帧的列数,我得到了一个原始形状的数据帧,而不是时间序列。

    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: 对于下列列表的仲裁长度: (这是我的用例) 应用 失败:

    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)
    

    我将熊猫0.21.1与python 3.4结合使用

    我试着玩 broadcast reduce 应用的参数,但没有成功。

    问题:

    • 在我的pandas版本中,是否有有效的apply语法来实现这一点?
    • 有什么关于失败原因的见解吗?
    • 是否有更好的解决方案/方法,同时使用numpy或其他panda函数?我目前的解决方案一点都不理想
    3 回复  |  直到 6 年前
        1
  •  1
  •   Haleemur Ali    6 年前

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

    tuple

    def foo(x):
        return tuple([i * x['B'] for i in x['A']])
    
    df.apply(foo, axis=1).apply(list)
    
    0      [1, 2]
    1         [6]
    2    [12, 15]
    dtype: object
    

        3
  •  1
  •   jezrael    6 年前

    pandas 0.23.1

    s = df.apply(foo, axis=1)
    print (s)
    0          [1, 2]
    1             [6]
    2    [12, 15, 18]
    dtype: object
    

    zip Series numpy 2d numpy array

    zipped = zip(df['A'], df['B'])
    a = pd.Series([[el * j for el in i] for i, j in zipped], index=df.index)
    print (a)
    0          [1, 2]
    1             [6]
    2    [12, 15, 18]
    dtype: object