简体   繁体   English

获取作为熊猫函数结果的列表

[英]Getting a list as the result of a function in pandas

I have data frame in pandas and I have written a function to use the information in each row to generate a new column.我在 Pandas 中有数据框,我编写了一个函数来使用每行中的信息生成一个新列。 I want the result to be in a list format:我希望结果采用列表格式:

      A    B    C
      3    4    1
      4    2    5

     def Computation(row):
          if row['B'] >= 3:
              return [s for s in range(row['C'],50)]
          else:
              return [s for s in range(row['C']+2,50)]

     df['D'] = df.apply(Computation, axis = 1) 

However, I am getting the following error:但是,我收到以下错误:

"could not broadcast input array from shape (308) into shape (9)" “无法将输入数组从形状(308)广播到形状(9)”

Could you please tell me how to solve this problem?你能告诉我如何解决这个问题吗?

Say you start with说你开始

In [25]: df = pd.DataFrame({'A': [3, 4], 'B': [4, 2], 'C': [1, 5]})

Then there are at least two ways to do it.那么至少有两种方法可以做到。

You can apply twice on the C column, but switch on the B column:您可以在C列上应用两次,但在B列上切换:

In [26]: np.where(df.B >= 3, df.C.apply(lambda c: [s for s in range(c, 50)]), df.C.apply(lambda c: [s for s in range(c + 2, 50)]))
Out[26]: 
array([ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
       [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]], dtype=object)

Or you can apply on the entire row and switch on the B value per row:或者您可以在整行上应用并打开每行的B值:

In [27]: df.apply(lambda r: [s for s in range(r.C, 50)] if r.B >= 3 else [s for s in range(r.C + 2, 50)], axis=1)
Out[27]: 
0    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14...
1    [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, ...

Note that the return types are different, but, in each case, you can still write请注意,返回类型是不同的,但是,在每种情况下,您仍然可以编写

df['foo'] = <each one of the above options>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM