【发布时间】:2018-12-23 05:20:51
【问题描述】:
我试图在通过 pandas 聚合时找到每列中最常出现的值。为了找到最常见的值,我按照建议 here 使用 value_counts,但面临性能问题(请参阅下面的 sn-p 代码)
import random
import time
import pandas as pd
df = pd.DataFrame({'Country_ID': [random.randint(1000, 100001) for i in
range(100000)],
'City': [random.choice(['NY', 'Paris', 'London',
'Delhi']) for i in range(100000)]})
agg_col = {'City': lambda x: x.value_counts().index[0]}
start = time.time()
df_agg = df.groupby('Country_ID').agg(agg_col)
print("Time Taken: {0}".format(time.time() - start))
print("Data: ", df_agg.head(5))
结果:
Time Taken: 24.467301845550537
Data:
City
Country_ID
1000 London
1001 Paris
1003 London
1004 London
1006 London
有什么办法可以提高上述性能?
【问题讨论】:
-
试过 scipy.stats
agg_col2 = {'City': lambda x: scipy.stats.mode(x)[0][0]}? -
pd.Series.mode怎么样?
标签: python python-3.x pandas pandas-groupby