python - 如何用其他列的下 n 个条目的最小值填充 DataFrame 列
问题描述
我有一个数据框:
import numpy as np
import pandas as pd
np.random.seed(18)
df = pd.DataFrame(np.random.randint(0,50,size=(10, 2)), columns=list('AB'))
df['Min'] = np.nan
n = 3 # can be changed
目前我使用迭代来做到这一点:
for row in range (0, df.shape[0]-n):
low = []
for i in range (1, n+1):
low.append(df.loc[df.index[row+i], 'B'])
df.loc[df.index[row], 'Min'] = min(low)
但这是一个相当缓慢的过程。请问有没有更有效的方法?谢谢你。
解决方案
df['Min'] = df['B'].rolling(n).min().shift(-n)
print (df)
A B Min
0 42 19 2.0
1 5 49 2.0
2 46 2 17.0
3 8 24 17.0
4 34 17 11.0
5 5 21 4.0
6 47 42 1.0
7 10 11 NaN
8 36 4 NaN
9 43 1 NaN
如果性能很重要,请使用此解决方案:
def rolling_window(a, window):
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
strides = a.strides + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
arr = rolling_window(df['B'].values, n).min(axis=1)
df['Min'] = np.concatenate([arr[1:], [np.nan] * n])
print (df)
A B Min
0 42 19 2.0
1 5 49 2.0
2 46 2 17.0
3 8 24 17.0
4 34 17 11.0
5 5 21 4.0
6 47 42 1.0
7 10 11 NaN
8 36 4 NaN
9 43 1 NaN
推荐阅读
- javascript - 提交表单呈现在不同的页面
- json - 如何更新 JSON 对象的属性
- c# - 如何将 ComboBox 的当前选择作为字符串获取
- javascript - 生成 >0 的随机整数,其给定浮点数的预期平均值 >0
- oauth - 使用自定义 Oauth 连接到 Snowflake 时对 invalid_client 错误进行故障排除
- branch.io - 分支未正确衡量来自 Google Ads 应用安装广告系列的安装事件
- r - 错误:在 Node.js 中执行 r-script 时产生 Rscript ENOENT
- git - 如何继续开发废弃的 GitHub 存储库(稍后合并它们的选项)?
- r - 在绘图图中制作自定义模式栏按钮图标
- python-2.7 - AWS Lambda:函数已成功创建,但创建触发器时出错:无法读取未定义的属性“包含”