在数据框中按日期对列上的均值进行矢量化

时间:2018-07-09 14:16:00

标签: python pandas

我正在为“ avgPrice”列创建每个不同日期的均值。数据是一个面板,其中包含以下用于不同“ typeID”的列。仅显示typeID 18的地方,整个数据集中有59个typeID。数据样本如下所示:

   typeID        date  lowPrice  highPrice  avgPrice  volume  orders
0      18  2003-10-01      14.0       14.0      14.0  284846      84
1      18  2003-10-02      14.0       16.0      15.0  533151      64
2      18  2003-10-03      15.0       15.0      15.0  247490      85
3      18  2003-10-04      15.0       15.0      15.0  367424     117
4      18  2003-10-05      14.0       14.0      14.0  923101     112

数据帧的长度为24574045,因此非常大。我想做的是创建一个汇总的avgPrice列,该列采用每个日期的每个typeID的avgPrice的未加权平均值。以下代码可以运行,但是执行时间非常慢:

dfm = pd.DataFrame()
total = len(set(df["date"])) # check execution time

for i, j in enumerate(set(df["date"])):
    if i % 10 == 0:
        print(i / total * 100) # check execution time
    dfm["date"] = j
    dfm["avgPrice"] = df.loc[df["date"] == j]["avgPrice"].mean()

这将返回一个新的数据框,该数据框具有所有日期和日期的所有typeID的avgPrice的未加权平均值。但是,考虑到手头数据的长度,这需要很长时间才能执行。有什么办法可以加快这个过程,例如向量化for循环?

0 个答案:

没有答案