简体   繁体   English

如何在 DataFrame 的所有行上应用函数

[英]How to apply a function on all rows of a DataFrame

I have a dataset as following我有一个数据集如下

data = { "C1": [1.0 , 1.2 , 1.2,  1.30 , 1.29 , 1.30,  1.31] ,
         "C2" :[1.2 , 1.3 , 1.3 , 1.40 , 1.50 , 1.60 , 1.61] ,
         "C3": [1.3 , 1.0 , 1.2 , 1.21 , 1.31 , 1.42 , 1.33] }

data = pd.DataFrame(data)
data = data.T
print(data)


          0    1    2     3     4     5     6
Cell 1  1.0  1.2  1.2  1.30  1.29  1.30  1.31
Cell 2  1.2  1.3  1.3  1.40  1.50  1.60  1.61
Cell 3  1.3  1.0  1.2  1.21  1.31  1.42  1.33

I have a function that finds the non-decreasing sequences in list of numbers.我有一个函数可以在数字列表中找到非递减序列。 For example if you consider the first row which is例如,如果您考虑第一行

[1.0 , 1.2 , 1.2,  1.30 , 1.29 , 1.30,  1.31]

there are two non-decreasing sequences:有两个非递减序列:

1- [1.0 , 1.2 , 1.2,  1.30] and 2- [1.29 , 1.30,  1.31]

I am using the following function to get these non-decreasing sequences:我正在使用以下函数来获取这些非递减序列:

def igroups(x):
    s = [0] + [i for i in range(1, len(x)) if x[i] < x[i-1]]  + [len(x)]
    #print(s)
    return [x[j:k] for j, k in [s[i:i+2] for i in range(len(s)-1)] if k - j > 1]

My question: I want to apply function igroups on all rows of my dataframe .我的问题:我想在igroups所有行apply函数igroups How can I do that?我怎样才能做到这一点? I have attempted solving this problem using apply , for example例如,我曾尝试使用apply解决此问题

dt.applymap(lambda x :  igroups(x))

I know apply function works on cells and not a row and the reason last line of code doesn't work is due to that, I also know that I can solve this problem using loops (which I prefer not to).我知道apply函数适用于单元格而不是一行,最后一行代码不起作用的原因是因为这个,我也知道我可以使用循环来解决这个问题(我不想这样做)。

The outcome of interest would be something such that there is a new column (new) that has the list of non-decreasing sequences of numbers:感兴趣的结果将是这样一个新列(新),其中包含非递减序列的列表:

0       1    2    3    4     5     6     7     new
Cell 1  1.0  1.2  1.2  1.30  1.29  1.30  1.31  [[1.0 , 1.2 , 1.2,  1.30 ], [1.29 , 1.30,  1.31]]
Cell 2  1.2  1.3  1.3  1.40  1.50  1.60  1.61  [[1.2 , 1.3 , 1.3 , 1.40 , 1.50 , 1.60 , 1.61]]
Cell 3  1.3  1.0  1.2  1.21  1.31  1.42  1.33  [[1.0 , 1.2 , 1.21 , 1.31 , 1.42]]
            

使用带有轴 = 1 的 pandas apply 。它将将该函数应用于每一行并返回一个系列。

df['new'] = df.apply(igroups, axis = 1)

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

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