Sim*_*mon 2 python mean dataframe pandas
假设我有一个Pandas数据框,如下所示:
import pandas as pd
import numpy as np
df = pd.DataFrame({"time": [100,200,300,400,100,200,300,np.nan],
"correct": [1,1,0,1,1,0,0,0]})
Run Code Online (Sandbox Code Playgroud)
印刷:
correct time
0 1 100.0
1 1 200.0
2 0 300.0
3 1 400.0
4 1 100.0
5 0 200.0
6 0 300.0
7 0 NaN
Run Code Online (Sandbox Code Playgroud)
我想计算的平均值time仅为行以下行,其中correct等于0.因此,在上述数据帧我想计算的平均值400,300以及NaN(这将给350)
我需要小心处理NaN值,以及最后一行有correct == 0但在其后面没有行的文字边缘情况
什么是最有效的方式在Pandas中执行此操作而不必诉诸循环数据框(我当前的实现)?
你可以使用shift()方法:
In [55]: df.loc[df.correct.shift() == 0, 'time'].mean()
Out[55]: 350.0
Run Code Online (Sandbox Code Playgroud)
说明:
In [53]: df.correct.shift()
Out[53]:
0 NaN
1 1.0
2 1.0
3 0.0
4 1.0
5 1.0
6 0.0
7 0.0
Name: correct, dtype: float64
In [54]: df.loc[df.correct.shift() == 0, 'time']
Out[54]:
3 400.0
6 300.0
7 NaN
Name: time, dtype: float64
Run Code Online (Sandbox Code Playgroud)