【问题标题】:Is it possible to create a for loop for a pandas df with 2 variables?是否可以为带有 2 个变量的 pandas df 创建一个 for 循环?
【发布时间】:2021-05-23 22:27:37
【问题描述】:

我有一个 pandas 数据框,其中包含基于不同用户(user_Id 列)和日期(日期列/pandas 数据对象)的重量(重量列)信息。

我想计算所有用户最早和最新测量的体重差异。

为了计算最早和最新的测量值,我使用了以下函数:

earliest_date = []
latest_date = []
for x in Id_list:
    a = weight_info[weight_info['Id']==x]
    earliest_date.append(a['date'].min())
    latest_date.append(a['date'].max())

然后我想创建一个 for 循环,以便传入日期和最早日期以获取重量信息,例如:

df = weight_info[(weight_info['date']==x) & (weight_info['Id']==y)]
df['weight']

但我不确定如何使用基于两个变量的 for 循环来执行此操作。或者有没有更简单的方法来运行整个计算?

【问题讨论】:

    标签: python pandas for-loop variables


    【解决方案1】:

    使用 groupby 获取每个用户的最小/最大日期

    min_dates = weight_info.groupby('Id').agg({'min':'date'})
    max_dates = weight_info.groupby('Id').agg({'max':'date'})
    

    然后加入权重以获得每个用户的最小/最大日期的权重

    min_weights = weight_info.merge( min_dates[['Id', 'date']], 
                                     on = ['Id', 'date'], how='inner' )
    
    max_weights = weight_info.merge( max_dates[['Id', 'date']], 
                                     on = ['Id', 'date'], how='inner' )
    

    最后,为同一个客户减去两者

    【讨论】:

    • 非常感谢,稍后再试试!到目前为止还不知道 .agg() 函数。几个月前刚学 Python。
    【解决方案2】:

    您可以尝试使用“pandasql”。该库允许您使用 SQL 代码操作 Pandas 数据框中的数据。我发现它对于处理随机 csv 文件中的数据帧很有用。

    import pandasql as psql
    
    df = 'Your_pandas_df'
    
    # Shows the record counts in your dataset
    record_count = psql.sqldf('''
    SELECT
    COUNT(*) as record_count
    FROM df''')
    

    【讨论】:

    • 非常感谢,我的SQL不是很高级,我试试看!
    猜你喜欢
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 2010-11-13
    • 2019-03-11
    • 2022-10-17
    • 2018-08-15
    相关资源
    最近更新 更多