小黑猪哈哈
2021-05-08 07:23
采纳率: 100%
浏览 47
已采纳

python中apply后如何输出一个dataframe而不是一整个serices?

def active_status(data):
    status = []
    for i in range(18):
        
        #若本月没有消费
        if data[i] == 0:
            if len(status) > 0:
                if status[i-1] == 'unreg':
                    status.append('unreg')
                else:
                    status.append('unactive')
            else:
                status.append('unreg')
        
        #若本月消费
        else:
            if len(status) == 0:
                status.append('new')
            else:
                if status[i-1] == 'unactive':
                    status.append('return')
                elif status[i-1] == 'unreg':
                    status.append('new')
                else:
                    status.append('active')
    return status



purchase_stats = df_purchase.apply(active_status,axis=1)
purchase_stats
#返回结果
user_id
1        [new, unactive, unactive, unactive, unactive, ...
2        [new, unactive, unactive, unactive, unactive, ...
3        [new, unactive, return, active, unactive, unac...
4        [new, unactive, unactive, unactive, unactive, ...
5        [new, active, unactive, return, active, active...
                               ...                        
23566    [unreg, unreg, new, unactive, unactive, unacti...
23567    [unreg, unreg, new, unactive, unactive, unacti...
23568    [unreg, unreg, new, active, unactive, unactive...
23569    [unreg, unreg, new, unactive, unactive, unacti...
23570    [unreg, unreg, new, unactive, unactive, unacti...
Length: 23570, dtype: object

df_purchase还是一个dataframe表格如下图(我的目的就是把下图的数字替换成一个个如"new"\"unreg"等的英文):

 

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

  • CSDN专家-HGJ 2021-05-08 10:18
    最佳回答

    对series再处理一下,构造成数据框。这样写,题主看看是不是能得到需要的结果。

    purchase_stats = pd.DataFrame(df_purchase.apply(active_status, axis=1).tolist(), index=df_purchase.index, columns=df_purchase.columns)
    print(purchase_stats)
    
    
    month  1997-01-01  ... 1997-04-01
    userid             ...
    23566       unreg  ...   unactive
    23577       unreg  ...   unactive
    23588       unreg  ...     active
    23589         new  ...     active
    评论
    解决 1 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题