OK_*_*_sr 2 python dataframe pandas feature-engineering
假设我们有以下带有列名的 df 。
df = pd.DataFrame({
'names':['Alan', 'Alan', 'John', 'John', 'Alan', 'Alan','Alan', np.nan, np.nan, np.nan, np.nan, np.nan, 'Christy', 'Christy','John']})
Run Code Online (Sandbox Code Playgroud)
>>> df
names
0 Alan
1 Alan
2 John
3 John
4 Alan
5 Alan
6 Alan
7 NaN
8 NaN
9 NaN
10 NaN
11 NaN
12 Christy
13 Christy
14 John
Run Code Online (Sandbox Code Playgroud)
我想在列上运行一个应用函数,该函数返回特定值出现的最大连续次数。起初,我想对 NaN 执行此操作,但扩展后想切换到列中的任何其他值。
解释:如果我们对 Nan 运行 apply,结果将为 5,因为 5 是 NaN 连续出现的最高次数。如果列中其他值后面有后续行,并且 NaN 连续出现超过 5 次,则结果就是这样。
如果我们运行 apply for Alan,结果将是 3,因为 3 将在连续 Alan 第一次出现时取代 2。
df_counts = df #create new df to keep the original
df_counts['names'].fillna("NaN", inplace=True) # replace np.nan with string
df_counts['counts'] = df.names.groupby((df.names != df.names.shift()).cumsum()).transform('size') # count consecutive names
df_counts = df_counts.sort_values('counts').drop_duplicates("names",keep='last') #keep only the highest counts
def get_counts(name):
return df_counts.loc[df['names'] == name, 'counts'].item()
Run Code Online (Sandbox Code Playgroud)
然后get_counts("Alan")就会回来3,并且get_counts("NaN")还会回来5。