如何删除iterrows()
?能不能用numpy或熊猫更快?你知道吗
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8)*0 })
print(df)
# A B C
# 0 foo one 0
# 1 bar one 0
# 2 foo two 0
# 3 bar three 0
# 4 foo two 0
# 5 bar two 0
# 6 foo one 0
# 7 foo three 0
selDict = {"foo":2, "bar":3}
这样做有效:
for i, r in df.iterrows():
if selDict[r["A"]] > 0:
selDict[r["A"]] -=1
df.set_value(i, 'C', 1)
print df
# A B C
# 0 foo one 1
# 1 bar one 1
# 2 foo two 1
# 3 bar three 1
# 4 foo two 0
# 5 bar two 1
# 6 foo one 0
# 7 foo three 0
有一种方法-
1)助手函数:
使用基于循环切片的辅助函数可能更快:
2)主要功能:
示例运行-
原始方法:
案例1:
案例2:
^{} 在这里可以帮忙。为了得到每个元素在其bucket中的秩,我们采用“min”和“ordinal”方法之间的差异:
那么我们就比较一下
df.A.map(selDict)
:这可能有点低效(调用rankdata两次),但是在scipy中使用优化的例程应该可以弥补这一点。你知道吗
如果您不能使用scipy,您可以对“ordinal”方法使用repeated
argsort()
,对“min”方法使用my solutionunique
和bincount
:然后与上面的
df.A.map(selDict)
进行比较。你知道吗如果我理解正确,您可以使用cumcount:
相关问题 更多 >
编程相关推荐