我基本上想学习一种基于正则表达式的条件切片切片Pandas数据帧的更快方法.例如,以下df(string_column中有4个以上的变体,它们仅用于说明目的):
index, string_col1, string_col2, value
0, 'apple', 'this', 10
1, 'pen', 'is', 123
2, 'pineapple', 'sparta', 20
3, 'pen pineapple apple pen', 'this', 234
4, 'apple', 'is', 212
5, 'pen', 'sparta', 50
6, 'pineapple', 'this', 69
7, 'pen pineapple apple pen', 'is', 79
8, 'apple pen', 'sparta again', 78
...
100000, 'pen pineapple apple pen', 'this is sparta', 392
Run Code Online (Sandbox Code Playgroud)
我必须使用正则表达式根据string_column进行布尔条件切片,同时在值列中找到最小值和最大值的索引,然后最终找到最小值和最大值之间的差值.我通过以下方法执行此操作,但是当我必须匹配许多不同的正则表达式模式时,它是超级缓慢的:
pat1 = re.compile('apple')
pat2 = re.compile('sparta')
mask = (df['string_col1'].str.contains(pat1)) & (df['string_col2'].str.contains(pat2))
max_idx = df[mask].idxmax()
min_idx = df[mask].idxmin()
difference = df['value'].loc[max_idx] …Run Code Online (Sandbox Code Playgroud) 我想使用 pandas apply() 而不是遍历数据帧的每一行,据我所知,这是更有效的过程。
我想做的很简单:
temp_arr = [0,1,2,3]
# I know this is not a dataframe, just want to show quickly how it looks like.
temp_df is a 4x4 dataframe, simply: [[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4]]
For each row in my temp_df, minus the corresponding number in the temp_arr.
Run Code Online (Sandbox Code Playgroud)
例如,我的数据帧中的第一行是 [1,1,1,1],我想从它们中减去 temp_arr 中的第一项(即 0),所以输出应该是 [1,1,1 ,1]。第二行是 [2,2,2,2],我想从它们中减去 temp_arr 中的第二项(即 1),所以输出也应该是 [1,1,1,1]。
如果我减去一个常数,我知道我可以很容易地做到这一点:
temp_df.apply(lambda x: x-1)
Run Code Online (Sandbox Code Playgroud)
但这里棘手的事情是我需要遍历我的 temp_arr 来获得减去的数字。有什么办法可以用apply()做到这一点?