Python:如何将数据框中的 3 列作为函数中的 3 个单独参数传递并遍历列值

标签 python function loops dataframe iteration

我有以下 python 数据框,其中列如下: 此数据帧存储到变量 WSI_Hourly

Date    Rain (in)            
1/5     2           
1/6     0          
1/7     7   
1/8     10    
1/9     13   
1/10    11   
1/11    1   

我正在尝试编写一个函数来创建一个新列,指定“Rain”值所属的动态范围桶。请参阅所需的输出表:

Date   Rain     Rain_Range    
1/5    2        0-5 inches
1/6    0        0-5 inches
1/7    7        6-10 inches
1/8    10       6-10 inches
1/9    13       11-15 inches
1/10   11       11-15 inches
1/11   1        0-5 inches 

下面是我的函数:

def precip(df, min_value, max_value, desc):
    if(min_value < max_value):
        for i, m in df.iterrows():
            if (m['Rain'] >= min_value) & (m['Rain'] <= max_value):
                df.set_value(i, 'Rain_Range', desc)

precip(WSI_Hourly, min_value, max_value, desc)

因为我想动态设置“Rain_Range”的值,所以我想通过表示 min_value、max_value 和 desc 参数的函数传递以下数据框。

请看下面的数据框表:

min_value   max_value   desc      
0           5           0-5 inches   
6           10          6-10 inches    
11          15          11-15 inches

我的问题是:如何将上面数据框中的 min_value、max_value 和 desc 列作为参数传递到我的函数中,以获取我的所需的输出表

*非常感谢对此的任何帮助

最佳答案

您可以使用 pd.cut 跳过您的函数。

一些数据:

from io import StringIO

import pandas as pd

dat=StringIO('''Date    Rain(in)            
1/5     2           
1/6     0          
1/7     7   
1/8     10    
1/9     13   
1/10    11   
1/11    1   ''')

cuts = StringIO('''min_value   max_value   desc      
0           5           0-5inches   
6           10          6-10inches    
11          15          11-15inches''')
df = pd.read_csv(dat, delim_whitespace = True)
cuts = pd.read_csv(cuts, delim_whitespace = True)

现在我们使用 pd.cut 函数“剪切”,使用来自“剪切”数据框的分箱和标签:

df['Rain_Range'] = pd.cut(df['Rain(in)'],\
        bins = pd.concat([cuts.min_value[:1]-1,cuts.max_value]),\
        labels = cuts.desc)

给出:

Date    Rain(in)    Rain_Range
1/5     2   0-5inches
1/6     0   0-5inches
1/7     7   6-10inches
1/8     10  6-10inches
1/9     13  11-15inches
1/10    11  11-15inches
1/11    1   0-5inches

关于Python:如何将数据框中的 3 列作为函数中的 3 个单独参数传递并遍历列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40941850/

相关文章:

python - 将 json 转换为 Graphite 烯 graphql 响应

python - 从管理员检测哪个模型创建并分配外键

android - Kotlin 编写了一个函数,可以检查可能的数十个值并使用 lambda 类型返回它们的非空值

javascript - 我的带有对象和方法的 JavaScript 代码无法正常工作

ios - 我可以在 swift 中有两种类型的参数吗?

android - 循环时听按钮

python - 转置 Pandas 数据透视表

Python - Pandas - 如何创建增量为 0.01 秒的日期时间序列?

linux - 应该打印文件名的循环返回空行

python - 为什么不分配给循环变量修改原始列表?如何循环分配回列表?