【问题标题】:Python: Apply code to an entire dataframe columnPython:将代码应用于整个数据框列
【发布时间】:2019-03-03 17:19:15
【问题描述】:

我在一个填充了值的数据框中有一列 col1。

                                col1                
row1      [0.0, 6.33839991, 3.93961207, 5.27702178, 8.27702178, 6.44343, 5.668574]             
row2      [0.0, 5.93961207, 4.27702178, 4.12702178]
row3      [0.0, 6.44428501, 3.93961207, 8.27702178, 4.27121178]

每一行包含一个系列。我需要一个新列,比如 col2,它返回一个新系列。该系列从 0 开始,每次递增 100,直到该系列与原始系列的长度匹配。

预期输出

                            col1                               col2          
row1      [0.0, 6.3, 3.93, 5.27, 8.2, 6.4, 5.6]             [0,100,200,300,400,500,600]                       
row2      [0.0, 5.9, 4.2, 4.1]                              [0,100,200,300]
row3      [0.0, 6.4, 3.9, 8.2, 4.2]                         [0,100,200,300,400]

谢谢!

【问题讨论】:

  • Lambda 不能包含分配
  • 您可以发布数据框吗?和期望值?它混淆了你想要什么并基于什么
  • 我已经更新了我的问题。我希望这很清楚!
  • 您的列表中有哪些重复项?
  • 重复并不重要。我只需要列表的总长度

标签: python pandas numpy dataframe


【解决方案1】:

试试:

def func(x):
    x['col2'] = np.arange(0, len(x['col1'])*100, 100)
    return x
df.apply(lambda x: func(x) , axis=1)

【讨论】:

  • 我编辑了代码以提高我想要做的事情的清晰度
  • 这段代码并没有解决我的问题,只是为了清楚
  • 这也是我的解决方案,它得到了所需的解决方案。不过,我把它浓缩成一条线:df['col2'] = df['col1'].apply(lambda x : np.arange(0, len(x)*100, 100))
  • 如果您觉得可以,请您将此标记为解决方案吗?
【解决方案2】:

我的建议是:

df['col2'] = df.col1.transform(lambda x: [ i * 100 for i in range(len(x))])

【讨论】:

    【解决方案3】:

    如果你想要基于每个唯一字符串(分解)的乘法,试试这个,对于列表的重复元素,这将返回重复的结果:

    df['col2']=df.col1.transform(lambda x: pd.factorize(x)[0]*100)
    

    或@jezrael 的建议:

    df.col1.apply(lambda x: np.arange(len(x))*100)
    
    
    print(df)
    
                                                       col1  \
    row1  [0.0, 6.33839991, 3.93961207, 5.27702178, 8.27...   
    row2          [0.0, 5.93961207, 4.27702178, 4.12702178]   
    row3  [0.0, 6.44428501, 3.93961207, 8.27702178, 4.27...   
    
                                       col2  
    row1  [0, 100, 200, 300, 400, 500, 600]  
    row2                 [0, 100, 200, 300]  
    row3            [0, 100, 200, 300, 400] 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      相关资源
      最近更新 更多