[英]python: pandas: filter one column and get the average of another column
[英]how to get the average of values for one column based on another column value in python (pandas, jupyter)
我希望能够根据“T”列中的过滤值获得“G”列中相应值的平均值。
所以我设置了 'T' 列的值,我想根据它对 'G' 列中的值求和,然后将总数除以计数以获得平均值,该平均值附加到一个变量中。 但是平均值没有正确计算。 看下面的截图
total=0
g_avg=[]
output=[]
counter=0
for i, row in df_new.iterrows():
if (row['T'] > 2):
counter+=1
total+=row['G']
if (counter != 0 and row['T']==10):
g_avg.append(total/counter)
counter = 0
total = 0
print(g_avg)
下面是一组更好的数据,因为在“T”值中有重复,所以当 T 值在某个范围内时,即从凌晨 2 点到上午 10 点等,我需要一个计数器来获得 G 值的平均值,抱歉它不允许我只粘贴数据集,所以我对它进行了剪辑
如果您想要T介于 2 和 7 之间时G列值的平均值:
df_new.loc[(df_new['T']>2) & (df_new['T']<7), 'G'].mean()
更新
如果没有任何预期的输出,很难确切地知道您想要什么。 如果你有一些看起来像这样的数据:
print(df)
T G
0 0 0
1 0 0
2 1 0
3 2 1
4 3 3
5 4 0
6 5 4
7 6 5
8 7 0
9 8 6
10 9 7
你想要这样的东西:
print(df)
T G
0 0 0
1 0 0
2 1 0
3 2 1
4 3 3
5 4 3
6 5 3
7 6 3
8 7 0
9 8 6
10 9 7
然后你可以使用布尔索引和DataFrame.loc
:
avg = df.loc[(df['T']>2) & (df['T']<7), 'G'].mean()
df.loc[(df['T']>2) & (df['T']<7), 'G'] = avg
print(df)
T G
0 0 0.0
1 0 0.0
2 1 0.0
3 2 1.0
4 3 3.0
5 4 3.0
6 5 3.0
7 6 3.0
8 7 0.0
9 8 6.0
10 9 7.0
更新 2
如果您有一些示例数据:
print(df)
T G
0 0 1
1 2 2
2 3 3
3 3 1
4 3 2
5 10 4
6 2 5
7 2 5
8 2 5
9 10 5
方法 1:要简单地获取这些方法的列表,您可以为您的时间间隔创建组并在m
过滤:
m = df['T'].between(0,5,inclusive=False)
g = m.ne(m.shift()).cumsum()[m]
lst = df.groupby(g).mean()['G'].tolist()
print(lst)
[2.0, 5.0]
方法 2:如果您想在它们各自的 T 值中包含这些均值,那么您可以这样做:
m = df['T'].between(0,5,inclusive=False)
g = m.ne(m.shift()).cumsum()
df['G_new'] = df.groupby(g)['G'].transform('mean')
print(df)
T G G_new
0 0 1 1
1 2 2 2
2 3 3 2
3 3 1 2
4 3 2 2
5 10 4 4
6 2 5 5
7 2 5 5
8 2 5 5
9 10 5 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.