Created
November 19, 2020 14:31
-
-
Save ki-chi/a3b8343ea37f5bbc2c2ecc95390e9edb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import numpy as np | |
import pandas as pd | |
def np_mode(df): | |
""" | |
与えられたDataFrameの各列から最頻値を返す | |
Original: https://twitter.com/nkay/status/1328231713919496194 | |
""" | |
arr = df.to_numpy() | |
max, min, ncol = arr.max(), arr.min(), arr.shape[1] | |
offset = np.arange(ncol) * (max-min+1) - min | |
return np.bincount((arr+offset).ravel()).reshape(ncol, -1).argmax(1) + min | |
nrow = 100 | |
ncol = 400_000 | |
np.random.seed(0) | |
df = pd.DataFrame(np.random.choice([-1,0,1],(nrow,ncol))) | |
t1 = time.time() | |
np_mode(df) | |
t2 = time.time() | |
print(f"elapsed time: {t2-t1}") | |
# elapsed time: 0.2317368984222412 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Julia ver. : https://gist.github.com/cac1e8d8e864c0d99148024a5cf15fed