【发布时间】:2019-02-05 15:43:56
【问题描述】:
我的 pandas/numpy 生锈了,我写的代码感觉效率低下。
我在 Python3.x 中初始化一个 numpy 零数组,长度为 1000。就我的目的而言,这些只是整数:
import numpy as np
array_of_zeros = np.zeros((1000, ), )
我还有以下DataFrame(比我的实际数据小很多)
import pandas as pd
dict1 = {'start' : [100, 200, 300], 'end':[400, 500, 600]}
df = pd.DataFrame(dict1)
print(df)
##
## start end
## 0 100 400
## 1 200 500
## 2 300 600
DataFrame 有两列,start 和 end。这些值表示一个值范围,即start 将始终是小于end 的整数。上面,我们看到第一行的范围是100-400,接下来是200-500,然后是300-600。
我的目标是逐行遍历 pandas DataFrame,并根据这些索引位置递增 numpy 数组 array_of_zeros。因此,如果在10 到20 的数据框中有一行,我想将索引 10-20 的零增加 +1。
这是我想做的代码:
import numpy as np
array_of_zeros = np.zeros((1000, ), )
import pandas as pd
dict1 = {'start' : [100, 200, 300], 'end':[400, 500, 600]}
df = pd.DataFrame(dict1)
print(df)
for idx, row in df.iterrows():
for i in range(int(row.start), int(row.end)+1):
array_of_zeros[i]+=1
而且它有效!
print(array_of_zeros[15])
## output: 0.0
print(array_of_zeros[600])
## output: 1.0
print(array_of_zeros[400])
## output: 3.0
print(array_of_zeros[100])
## output: 1.0
print(array_of_zeros[200])
## output: 2.0
我的问题:这是非常笨拙的代码!我不应该在 numpy 数组中使用这么多 for 循环!如果输入数据帧非常大,此解决方案将非常低效
是否有更有效(即更基于 numpy)的方法来避免这种 for 循环?
for i in range(int(row.start), int(row.end)+1):
array_of_zeros[i]+=1
也许有面向 pandas 的解决方案?
【问题讨论】:
标签: python python-3.x pandas numpy