python - pandas DataFrame 中的操作

标签 python pandas statistics dataframe

我有一个相当大(~5000行)的DataFrame,有很多变量,比如2个['max', 'min'],按4个参数排序,['Hs', 'Tp', 'wd' ,“种子”]。它看起来像这样:

>>> data.head()
   Hs  Tp   wd  seed  max  min
0   1   9  165    22  225   18
1   1   9  195    16  190   18
2   2   5  165    43  193   12
3   2  10  180    15  141   22
4   1   6  180    17  219   18
>>> len(data)
4500

我只想保留前 2 个参数,并获取为每个“wd”单独计算的所有“种子”的最大标准偏差。

最后,我留下了唯一的(Hs,Tp)对,其中每个变量都有最大标准差。像这样的东西:

>>> stdev.head()
  Hs Tp       max       min
0  1  5  43.31321  4.597629
1  1  6  43.20004  4.640795
2  1  7  47.31507  4.569408
3  1  8  41.75081  4.651762
4  1  9  41.35818  4.285991
>>> len(stdev)
30

下面的代码做了我想要的,但由于我对 DataFrames 知之甚少,我想知道这些嵌套循环是否可以以不同的、更 DataFramy 的方式完成 =)

import pandas as pd
import numpy as np

#
#data = pd.read_table('data.txt')
#
# don't worry too much about this ugly generator,
# it just emulates the format of my data...
total = 4500
data = pd.DataFrame()
data['Hs'] = np.random.randint(1,4,size=total)
data['Tp'] = np.random.randint(5,15,size=total)
data['wd'] = [[165, 180, 195][np.random.randint(0,3)] for _ in xrange(total)]
data['seed'] = np.random.randint(1,51,size=total)
data['max'] = np.random.randint(100,250,size=total)
data['min'] = np.random.randint(10,25,size=total)

# and here it starts. would the creators of pandas pull their hair out if they see this?
# can this be made better?
stdev = pd.DataFrame(columns = ['Hs', 'Tp', 'max', 'min'])
i=0
for hs in set(data['Hs']):
    data_Hs = data[data['Hs'] == hs]
    for tp in set(data_Hs['Tp']):
        data_tp = data_Hs[data_Hs['Tp'] == tp]
        stdev.loc[i] = [
               hs, 
               tp, 
               max([np.std(data_tp[data_tp['wd']==wd]['max']) for wd in set(data_tp['wd'])]), 
               max([np.std(data_tp[data_tp['wd']==wd]['min']) for wd in set(data_tp['wd'])])]
        i+=1

谢谢!

PS:如果好奇的话,这是根据海浪变化的变量统计数据。 Hs 是波高,Tp 波周期,wd 波向,种子代表不规则波列的不同实现,min 和 max 是特定暴露时间内的峰值或 my 变量。毕竟,通过标准差和平均值,我可以对数据进行一些分布拟合,就像 Gumbel 一样。

最佳答案

如果我没理解错的话,这可能是一句俏话:

data.groupby(['Hs', 'Tp', 'wd'])[['max', 'min']].std(ddof=0).max(level=[0, 1])

(如果需要,请在末尾添加 reset_index())

关于python - pandas DataFrame 中的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31272726/

相关文章:

python - 从午夜以外的时间开始重新采样每日 Pandas 时间序列

python - 从 2 个列表中查找相关系数

python - 快速计算在整数范围内定义的函数的总和 - (0,2^52)

python - 从 PostgreSQL 中的 PL/Python 函数调用 plpgsql 函数

python - 读取用户上传的CSV文件的数据

python - 在 While 循环中从 Pandas Dataframe 中查找特定的数据行

python - 如何将自定义列顺序(在分类上)应用于 Pandas 箱线图?

r - 使用发布包将 Cox 回归结果导出到 Excel 或 Word

python - Zed 的 Learn Python the Hard way 练习 25 中的 'import' key

python - 如何获取 lxml.etree 的父标签属性,如 'KEY' 、 'NAME' 、 Python 3.6