猿问

Large Pandas Dataframe 中一小部分值的频率

这个问题提供了一个示例,说明如何使用 pd.get_dummies + 聚合从 pandas 数据帧获取给定行的频率计数。但是,如果您只需要一个非常大的数据帧中的一小部分术语,则这无法扩展。

例如考虑相同的例子:

import pandas as pd


df = pd.DataFrame({'ID': ['xyz_1', 'xyz_2', 'xyz_3', 'xyz_4', 'xyz_400'],

                   'class1': ['yes_1', 'no_2', pd.NA, 'no_3', 'no_7'],

                   'class2': ['no_8', 'yes_15', 'yes_16', 'no_18', 'no_21'],

                   'class3': [pd.NA, 'no_51', 'yes_1', 'no_3', 'no_4'],

                   'class100': ['yes_3', 'no_5', pd.NA, 'yes_6', 'no_7']})


        ID class1  class2 class3 class100

0    xyz_1  yes_1    no_8   <NA>    yes_3

1    xyz_2   no_2  yes_15  no_51     no_5

2    xyz_3   <NA>  yes_16  yes_1     <NA>

3    xyz_4   no_3   no_18   no_3    yes_6

4  xyz_400   no_7   no_21   no_4     no_7

它们可以是许多不同的 calcategori 变量之一,而不是位于 yes 和 no 集合中的值。如果您只想 yes_1、no_51 的频率项,这将需要大量的额外计算。


到目前为止我发现的最好的解决方案是将其他值预处理为 NAN


set = ['yes_1', 'no_51']

df[~df.isin(set)] = pd.NA


     ID class1 class2 class3 class100

0  <NA>  yes_1   <NA>   <NA>     <NA>

1  <NA>   <NA>   <NA>  no_51     <NA>

2  <NA>   <NA>   <NA>  yes_1     <NA>

3  <NA>   <NA>   <NA>   <NA>     <NA>

4  <NA>   <NA>   <NA>   <NA>     <NA>

对于 100 万个条目的大型数据帧来说,这仍然非常缓慢。有没有办法更好地扩展它。


慕尼黑的夜晚无繁华
浏览 165回答 3
3回答

红糖糍粑

在链接的问题中,性能更高的解决方案是:df.apply(lambda&nbsp;row:&nbsp;row.value_counts(dropna=False),&nbsp;axis=1).fillna(0)这可能已经足以满足您的目的;但是,如果您只需要几个值,则可能会更快:counts&nbsp;=&nbsp;pd.Series({(df&nbsp;==&nbsp;key).values.sum()&nbsp;for&nbsp;key&nbsp;in&nbsp;['yes_1',&nbsp;'no_51']})

12345678_0001

我不知道它是否比你的技术更好,但我建议将其作为测试的解决方案:(&nbsp; &nbsp; pd&nbsp; &nbsp; .melt(df,id_vars=['ID'])&nbsp; &nbsp; .assign(yes_1 = lambda x: np.where(x['value']=='yes_1',1,0))&nbsp; &nbsp; .assign(no_51 = lambda x: np.where(x['value']=='no_51',1,0))&nbsp; &nbsp; .sum())

肥皂起泡泡

df.set_index('ID', inplace=True)#Set ID as indexdf[~df.isin(['yes_1', 'no_51'])] = np.nan#Set anything not in the set as nanpd.get_dummies(df.stack().unstack())#get dummies from a datframe that has dropped anycolumns with NaNS&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; class1_yes_1&nbsp; class3_no_51&nbsp; class3_yes_1ID&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;xyz_1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0xyz_2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0xyz_3&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1
随时随地看视频慕课网APP

相关分类

Python
我要回答