我有一个非常大的数据框(〜10 ^ 8行),需要在其中更改一些值。我使用的算法很复杂,因此我尝试将问题分解为以下简单示例。我主要使用C ++进行编程,因此我一直在考虑for循环。我知道我应该向量化,但是我是python的新手,但是对pandas来说是新手,因此无法提出更好的解决方案。任何提高性能的解决方案都是值得欢迎的。
#!/usr/bin/python3
import numpy as np
import pandas as pd
data = {'eventID': [1, 1, 1, 2, 2, 3, 4, 5, 6, 6, 6, 6, 7, 8],
'types': [0, -1, -1, -1, 1, 0, 0, 0, -1, -1, -1, 1, -1, -1]
}
mydf = pd.DataFrame(data, columns=['eventID', 'types'])
print(mydf)
MyIntegerCodes = np.array([0, 1])
eventIDs = np.unique(mydf.eventID.values) # can be up to 10^8 values
for val in eventIDs:
currentTypes = mydf[mydf.eventID == val].types.values
if (0 in currentTypes) & ~(1 in currentTypes):
mydf.loc[mydf.eventID == val, 'types'] = 0
if ~(0 in currentTypes) & (1 in currentTypes):
mydf.loc[mydf.eventID == val, 'types'] = 1
print(mydf)
有任何想法吗?
编辑:我被要求解释我对我的for循环。对于每个eventID,我想知道所有对应的类型是否都包含1或0或两者都包含。如果它们包含1,则所有等于-1的值都应更改为1。如果值是0,则等于-1的所有值都应更改为0。我的问题是要为每个eventID高效地单独执行此操作。每个eventID可以有一个或多个条目。
输入示例:
eventID types
0 1 0
1 1 -1
2 1 -1
3 2 -1
4 2 1
5 3 0
6 4 0
7 5 0
8 6 -1
9 6 -1
10 6 -1
11 6 1
12 7 -1
13 8 -1
示例输出:
eventID types
0 1 0
1 1 0
2 1 0
3 2 1
4 2 1
5 3 0
6 4 0
7 5 0
8 6 1
9 6 1
10 6 1
11 6 1
12 7 -1
13 8 -1
首先,我们创建布尔面具m1
和m2
使用Series.eq
,然后使用DataFrame.groupby
这个掩模,通过变换any
,然后使用np.select
从选择的内容1, 0
取决于条件m1 or m2
:
m1 = mydf['types'].eq(1).groupby(mydf['eventID']).transform('any')
m2 = mydf['types'].eq(0).groupby(mydf['eventID']).transform('any')
mydf['types'] = np.select([m1 , m2], [1, 0], mydf['types'])
结果:
# print(mydf)
eventID types
0 1 0
1 1 0
2 1 0
3 2 1
4 2 1
5 3 0
6 4 0
7 5 0
8 6 1
9 6 1
10 6 1
11 6 1
12 7 -1
13 8 -1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句