【发布时间】:2022-10-18 19:21:22
【问题描述】:
我有一个 Pandas DataFrame,包含“时间”和“当前”列。它还有很多其他列,但我不想将它们用于此操作。所有值都是浮点数。
df[['time','current']].head()
time current
1 0.0 9.6
2 300.0 9.3
3 600.0 9.6
4 900.0 9.5
5 1200.0 9.5
我想计算电流随时间的滚动积分,这样在每个时间点,我都会得到电流随时间变化的积分。 (我意识到这个特定的操作很简单,但它是一个例子。我不是真的在寻找这个功能,而是整个方法)
理想情况下,我可以做这样的事情:
df[['time','current']].expanding().apply(scipy.integrate.trapezoid)
或者
df[['time','current']].expanding(method = 'table').apply(scipy.integrate.trapezoid)
但这些都不起作用,因为我想将“时间”列作为函数的第一个参数,将“当前”作为第二个参数。该函数确实适用于一列(仅当前),但我不喜欢之后分别除以时间步长。
在expanding().apply() 中似乎无法访问DataFrame 列。 我听说在内部扩展被视为一个数组,所以我也试过这个:
df[['time','current']].expanding(method = 'table').apply(lambda x:scipy.integrate.trapezoid(x[0], x[1]))
df[['time','current']].expanding(method = 'table').apply(lambda x:scipy.integrate.trapezoid(x['time'], x['current']))
和变体,但我永远无法访问扩展()中的列。
事实上,即使在普通 DataFrame 上使用 apply() 也不允许同时使用列,因为每个列都被顺序视为一个系列。
df[['time','current']].apply(lambda x:scipy.integrate.trapezoid(x.time,x.current))
...
AttributeError: 'Series' object has no attribute 'time'
This answer 提到了用于扩展()的方法“表”,但当时还没有出来,我似乎无法弄清楚它在这里需要什么。他们的解决方案只是手动完成。
我也尝试过先定义函数,但这也会返回错误:
def func(x,y):
return(scipy.integrate.trapezoid(x,y))
df[['time','current']].expanding().apply(func)
...
DataError: No numeric types to aggregate
扩展().apply()甚至可以实现我的要求吗?我应该换一种方式吗?我可以申请扩展吗里面应用()?
谢谢,祝你好运。
【问题讨论】:
-
scipy.integrate.cumtrapz已经是累积(扩展)计算,所以就使用它? -
@ALollz 我不知道,我会调查一下。但这并不能真正解决一般问题。不过谢谢。
标签: python pandas dataframe apply