gpt4 book ai didi

python - 检索 Python DataFrame 中的平均值

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

我有质量pandas数据帧 df :

year          count
1983 5
1983 4
1983 7
...
2009 8
2009 11
2009 30
我的目标是每个 year 采样 10 个数据点100次得到 count的均值和标准差每年。 count的标志值是随机确定的。

我想每个 year 随机抽样 10 个数据,这可以通过:
new_df = pd.DataFrame(columns=['year', 'count'])
ref = df.year.unique()

for i in range(len(ref)):
appended_df = df[df['year'] == ref[i]].sample(n=10)
new_df = pd.concat([new_df,appended_df])
然后,我为 count 分配一个符号随机(以便随机机会 count 可以是正数或负数)并将其重命名为 value ,这可以通过:
vlist = []

for i in range(len(new_df)):
if randint(0,1) == 0:
vlist.append(new_df.count.iloc[i])
else:
vlist.append(new_df.count.iloc[i] * -1)

new_data['value'] = vlist
获取每个 year 的均值和标准差很简单:
xdf = new_data.groupby("year").agg([np.mean, np.std]).reset_index()
但是我似乎无法找到一种最佳方法来尝试每个 year 进行 100 次采样。 ,存储平均值,并获得每年这 100 个平均值的平均值和标准差。我可以考虑使用 for循环,但它会花费太多的运行时间。
本质上,输出应采用以下形式(此处 value 是任意的):
year      mean_of_100_means  total_sd
1983 4.22 0.43
1984 -6.39 1.25
1985 2.01 0.04
...
2007 11.92 3.38
2008 -5.27 1.67
2009 1.85 0.99
任何见解将不胜感激。

最佳答案

我认为你可以使用 Pandas groupbysample函数一起从 DataFrame 的每一年中获取 10 个样本。如果你把它放在一个循环中,那么你可以采样 100 次,然后合并结果。
听起来您只需要 100 个均值的标准差(并且您不需要 10 个观测值的样本的标准差),因此您可以只计算 groupby 和样本中的均值,然后计算标准差从当您创建最终 DataFrame 的 total_sd 列时,这 100 个中的每一个都表示。

import numpy as np
import pandas as pd

np.random.seed(42)

## create a random DataFrame with 100 entries for the years 1980-1999, length 2000
df = pd.DataFrame({
'year':[year for year in list(range(1980, 2000)) for _ in range(100)],
'count':np.random.randint(1,100,size=2000)
})

list_of_means = []

## sample 10 observations from each year, and repeat this process 100 times, storing the mean for each year in a list
for _ in range(100):
df_sample = df.groupby("year").sample(10).groupby("year").mean()
list_of_means.append(df_sample['count'].tolist())
array_of_means = [np.array(x) for x in list_of_means]

result = pd.DataFrame({
'year': df.year.unique(),
'mean_of_100_means': [np.mean(k) for k in zip(*array_of_means)],
'total_sd': [np.std(k) for k in zip(*array_of_means)]
})
这导致:
>>> result
year mean_of_100_means total_sd
0 1980 50.316 8.656948
1 1981 48.274 8.647643
2 1982 47.958 8.598455
3 1983 49.357 7.854620
4 1984 48.977 8.523484
5 1985 49.847 7.114485
6 1986 47.338 8.220143
7 1987 48.106 9.413085
8 1988 53.487 9.237561
9 1989 47.376 9.173845
10 1990 46.141 9.061634
11 1991 46.851 7.647189
12 1992 49.389 7.743318
13 1993 52.207 9.333309
14 1994 47.271 8.177815
15 1995 52.555 8.377355
16 1996 47.606 8.668769
17 1997 52.584 8.200558
18 1998 51.993 8.695232
19 1999 49.054 8.178929

关于python - 检索 Python DataFrame 中的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68148468/

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