gpt4 book ai didi

python - 如何根据python(pandas,jupyter)中的另一列值获取一列的平均值

转载 作者:行者123 更新时间:2023-12-04 04:18:51 24 4
gpt4 key购买 nike

the image shows the test dataset I am using to verify if the right averages are being calculated.

我希望能够根据“T”列中的过滤值获得“G”列中相应值的平均值。

因此,我设置了“T”列的值,我希望根据这些值对“G”列中的值求和,然后将总数除以计数以获得平均值,该平均值被附加到一个变量。但是平均值计算不正确。见下文 screenshot

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 值的平均值我等 sorry it wont allow me to just paste the dataset so ive took a snippy of it

最佳答案

如果您想要 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

然后您可以使用 bool 索引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

关于python - 如何根据python(pandas,jupyter)中的另一列值获取一列的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59934129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com