矢量化:如何避免两个 for 循环?
Vectorization : How do I avoid two for-loops?
通过这个 post,我正在寻找输入来向量化我的 python 代码,该代码当前使用两个 for 循环。出于性能原因,我想避免使用 for 循环。我当前的工作 python 代码如下所示。
代码有什么作用?
我有一个带有 c1 列的输入数据框,它有 4 行 10 行和三行 20 行。 c2 列是另一列带有一些随机数的列。
预期输出:我的 window 大小为 2。因此,对于 c1 = 10 或 c1=20 的每 2 行,我必须计算相应列 c2 的平均值。我附上了输入和预期输出的屏幕截图。
目前,我正在使用两个 for 循环实现此目的。
输入数据框截图:input dataframe
预期输出截图:expected output
我当前的Python代码:
import pandas as pd
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
df.head()
window = 2
allDF = 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 output
allDF.head()
可能有更短、更简单的方法来执行转换。但这里有一种避免循环的方法。
# 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
通过这个 post,我正在寻找输入来向量化我的 python 代码,该代码当前使用两个 for 循环。出于性能原因,我想避免使用 for 循环。我当前的工作 python 代码如下所示。
代码有什么作用? 我有一个带有 c1 列的输入数据框,它有 4 行 10 行和三行 20 行。 c2 列是另一列带有一些随机数的列。
预期输出:我的 window 大小为 2。因此,对于 c1 = 10 或 c1=20 的每 2 行,我必须计算相应列 c2 的平均值。我附上了输入和预期输出的屏幕截图。
目前,我正在使用两个 for 循环实现此目的。
输入数据框截图:input dataframe 预期输出截图:expected output
我当前的Python代码:
import pandas as pd
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
df.head()
window = 2
allDF = 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 output
allDF.head()
可能有更短、更简单的方法来执行转换。但这里有一种避免循环的方法。
# 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