我有一个格式为的数据框
id time a b
01 01 1 0
01 01 0 1
01 01 0 0
01 02 0 0
01 02 1 0
01 03 1 0
01 03 0 1
所以现在,输出应该是
id time a b
01 01 1 1
01 02 1 0
01 03 1 1
在这里,我基本上合并具有相同 id
和 time
的所有行,这样其他行中的值是该 id< 的所有值的最大值
和时间
。
我现在正在做
df = df.groupby(['id','time']).max()
但是,由于行数和列数很大,这需要花费大量时间(>10 分钟)。我想知道是否有更有效的方法来做同样的事情!
最佳答案
如果您的硬件允许您同时在多个内核上工作,并按组并行计算max
,您可能希望利用多处理
:
使用具有 25 列的随机样本和 ['id', 'time']
作为 MultiIndex
::
cols = {'id': np.random.randint(1, 11, 10000), 'time': np.random.randint(1, 11, 10000)}
cols.update({k: np.random.random(size=10000) for k in range(25)})
df = pd.DataFrame(cols).set_index(['id', 'time'])
<class 'pandas.core.frame.DataFrame'>
MultiIndex: 10000 entries, (4, 9) to (3, 4)
Data columns (total 25 columns):
0 10000 non-null float64
1 10000 non-null float64
2 10000 non-null float64
3 10000 non-null float64
4 10000 non-null float64
....
20 10000 non-null float64
21 10000 non-null float64
22 10000 non-null float64
23 10000 non-null float64
24 10000 non-null float64
dtypes: float64(25)
memory usage: 2.0+ MB
接下来,按['id', 'time']
级别分组并捕获组 ID:
grps = df.groupby(level=['id', 'time'])
index = [grp[0] for grp in grps]
结果为 100 个组:
'# Groups: ', len([grp[0] for grp in grps])
# Groups: 100
最后,设置一个包含 8 个工作线程(# 个核心)的 Pool
,并通过 functools.partial
在池中运行 100 个组,以传递 axis=0
参数:
from multiprocessing import Pool
from functools import partial
with Pool(processes=8) as pool:
imap_res = pool.imap(partial(np.amax, axis=0), [grp[1] for grp in grps])
通过列表理解
将结果连接回DataFrame
:
result = pd.concat([pd.Series(res) for res in imap_res], axis=1).T.sort_index(axis=1)
result.index = index
<class 'pandas.core.frame.DataFrame'>
Index: 100 entries, (1, 1) to (10, 10)
Data columns (total 25 columns):
0 100 non-null float64
1 100 non-null float64
2 100 non-null float64
3 100 non-null float64
4 100 non-null float64
....
20 100 non-null float64
21 100 non-null float64
22 100 non-null float64
23 100 non-null float64
24 100 non-null float64
dtypes: float64(25)
memory usage: 20.3+ KB
关于python - 合并pandas中具有相同id和时间的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34498339/