亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

矢量化:如何避免兩個 for 循環?

矢量化:如何避免兩個 for 循環?

泛舟湖上清波郎朗 2023-05-16 14:38:41
通過這篇文章,我正在尋找輸入來矢量化我的 python 代碼,該代碼目前使用兩個 for 循環。出于性能原因,我想避免使用 for 循環。我當前的工作 python 代碼如下所示。代碼有什么作用?我有一個帶有 c1 列的輸入數據框,它有 4 行 10 行和三行 20 行。c2 列是另一列帶有一些隨機數的列。預期輸出:我的窗口大小為 2。因此,對于 c1 = 10 或 c1=20 的每 2 行,我必須計算相應列 c2 的平均值。我附上了輸入和預期輸出的屏幕截圖。目前,我正在使用兩個 for 循環來實現這一點。輸入數據框截圖:輸入數據框 預期輸出截圖:預期輸出我當前的 Python 代碼:import pandas as pddata = [{'c1':10, 'c2':10},{'c1':10,'c2':20},{'c1':10,'c2':30},{'c1':10,'c2':40},       {'c1':20,'c2':50},{'c1':20,'c2':60},{'c1':20,'c2':70}]df = pd.DataFrame(data) # df = Inputdf.head() window = 2allDF = pd.DataFrame()records = df['c1'].unique()for x in records:    intervalsDF = pd.DataFrame(columns=['c1','meanc2'])    df2 = df.loc[df['c1'] == x]    for i in range(0, len(df2), window):        intervalIndex = len(intervalsDF)        interval = df2[i:i+window]        c1 = list(interval['c1'])[0]        meanc2 = interval['c2'].mean()        intervalSummary = [c1,meanc2]        intervalsDF.loc[intervalIndex] = intervalSummary    allDF = allDF.append(intervalsDF) # allDF is the expected outputallDF.head()
查看完整描述

1 回答

?
aluckdog

TA貢獻1847條經驗 獲得超7個贊

可能有一種更短、更簡單的方法來執行轉換。但這里有一種避免循環的方法。


# create the data frame, as per the original post

data = [{'c1':10, 'c2':10},

        {'c1':10,'c2':20},

        {'c1':10,'c2':30},

        {'c1':10,'c2':40},

        {'c1':20,'c2':50},

        {'c1':20,'c2':60},

        {'c1':20,'c2':70}

]

df = pd.DataFrame(data) # df = Input


# 1. convert the index to an ordinary column

df = df.reset_index()


# 2. 'helper' is a column that counts 0, 1, 2, 3, ... 

#     and re-starts for each c1

df['helper'] = df['index'] - df.groupby('c1')['index'].transform(min)


# 3. integer division on 'helper', to get 0, 0, 1, 1, 2, 2, ... 

# (identify non-overlapping pairs)

df['helper'] //= 2


# 4. now convert 'index' from ordinary column back to an Index

df = df.set_index('index')


# 5. compute the mean of c2 for value of 'c1' and each pair of observations

df = df.groupby(['c1', 'helper'])['c2'].mean()


# 6. re-order 'helper' and 'c1' to match order in output

df.index = df.index.swaplevel()


print(df)


helper  c1

0       10    15

1       10    35

0       20    55

1       20    70

Name: c2, dtype: int64


查看完整回答
反對 回復 2023-05-16
  • 1 回答
  • 0 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號