【问题标题】:Pandas column of lists, append a new column to each listPandas 列表列,为每个列表附加一个新列
【发布时间】:2023-03-11 11:58:02
【问题描述】:

例如,我得到了一个 pd.Series 列表,如下所示

test = pd.Series([[1, 0, 0, 0],[0, 1, 0, 0],[0, 1, 0, 0],[0, 0, 0, 1],[1, 0, 0, 0]])
print(test)
0    [1, 0, 0, 0]
1    [0, 1, 0, 0]
2    [0, 1, 0, 0]
3    [0, 0, 0, 1]
4    [1, 0, 0, 0]

我想要做的是,我想将每个元素的(索引 + 1)添加到每个列表中,比如

0    [1, 0, 0, 0, 1]
1    [0, 1, 0, 0, 2]
2    [0, 1, 0, 0, 3]
3    [0, 0, 0, 1, 4]
4    [1, 0, 0, 0, 5]

我怎样才能做到这一点?

【问题讨论】:

    标签: python pandas numpy numpy-ndarray


    【解决方案1】:
    test = pd.Series([[1, 0, 0, 0],[0, 1, 0, 0],[0, 1, 0, 0],
                      [0, 0, 0, 1],[1, 0, 0, 0]])
    b=0
    for a in test:
        b+=1
        a.append(b)
    print(test)
    

    会给

    0    [1, 0, 0, 0, 1]
    1    [0, 1, 0, 0, 2]
    2    [0, 1, 0, 0, 3]
    3    [0, 0, 0, 1, 4]
    4    [1, 0, 0, 0, 5]
    

    【讨论】:

      【解决方案2】:

      您可以尝试将此pd.Serieslist 理解一起使用:

      import pandas as pd
      test = pd.Series([[1, 0, 0, 0],[0, 1, 0, 0],[0, 1, 0, 0],[0, 0, 0, 1],[1, 0, 0, 0]])
      print(test + pd.Series([[i + 1] for i in test.index]))
      

      输出:

      0    [1, 0, 0, 0, 1]
      1    [0, 1, 0, 0, 2]
      2    [0, 1, 0, 0, 3]
      3    [0, 0, 0, 1, 4]
      4    [1, 0, 0, 0, 5]
      dtype: object
      

      【讨论】:

      • 我已经投票了,但似乎当我运行“pd.Series([[i + 1] for i in test.index])”时,它返回错误“TypeError: 'builtin_function_or_method '对象不可迭代"
      • @NicolasH 试试:print(test + pd.Series([[i + 1] for i in test.index()]))
      【解决方案3】:

      np.column_stack

      将索引堆叠到现有列表分配回原地测试:

      test[:] = np.column_stack([test.tolist(), test.index + 1]).tolist()
      test
       
      0    [1, 0, 0, 0, 1]
      1    [0, 1, 0, 0, 2]
      2    [0, 1, 0, 0, 3]
      3    [0, 0, 0, 1, 4]
      4    [1, 0, 0, 0, 5]
      dtype: object
      

      在这里,Series 被转换为列表列表,然后与 (index + 1) 连接。分配回来时,您需要使用列表列表,因为如果您要分配 numpy 数组,pandas 不明白您想要一列列表。


      Series.mapitertools.count

      另一种选择,使用 itertools 玩得开心:

      from itertools import count
      
      c = count(1)
      test.map(lambda l: [*l, next(c)])
      
      0    [1, 0, 0, 0, 1]
      1    [0, 1, 0, 0, 2]
      2    [0, 1, 0, 0, 3]
      3    [0, 0, 0, 1, 4]
      4    [1, 0, 0, 0, 5]
      dtype: object
      

      【讨论】:

        猜你喜欢
        • 2019-03-03
        • 2015-01-31
        • 2012-12-20
        • 2017-08-29
        • 1970-01-01
        • 2021-03-20
        • 2019-09-29
        • 1970-01-01
        相关资源
        最近更新 更多