首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >pandas dataframe如何根据日期移动行

pandas dataframe如何根据日期移动行
EN

Stack Overflow用户
提问于 2020-08-19 03:34:44
回答 1查看 43关注 0票数 0

我正在努力评估促销活动对我们客户的影响。我们的目标是从促销提供的角度来评估收入。然而,在不同的时间点为不同的客户提供了促销。如何将数据重新排列为Month 0Month 1Month 2Month 3Month 0是客户第一次获得促销的月份。

EN

回答 1

Stack Overflow用户

发布于 2020-08-19 04:56:25

使用以下不言自明的代码,您可以获得所需的输出:

代码语言:javascript
运行
复制
# Create DataFrame
import pandas as pd
df = pd.DataFrame({"Account":[1,2,3,4,5,6],\
"May-18":[181,166,221,158,210,159],\
"Jun-18":[178,222,230,189,219,200],\
"Jul-18":[184,207,175,167,201,204],\
"Aug-18":[161,174,178,233,223,204],\
"Sep-18":[218,209,165,165,204,225],\
"Oct-18":[199,206,205,196,212,205],\
"Nov-18":[231,196,189,218,234,235],\
"Dec-18":[173,178,189,218,234,205],\
"Promotion Month":["Sep-18","Aug-18","Jul-18","May-18","Aug-18","Jun-18"]})
df = df.set_index("Account")
cols = ["May-18","Jun-18","Jul-18","Aug-18","Sep-18","Oct-18","Nov-18","Dec-18","Promotion Month"]
df = df[cols]

# Define function to select the four months after promotion
def selectMonths(row):
    cols = df.columns.to_list()
    colMonth0 = cols.index(row["Promotion Month"])
    colsOut = cols[colMonth0:colMonth0+4]
    out = pd.Series(row[colsOut].to_list())
    return out

# Apply the function and set the index and columns of output DataFrame
out = df.apply(selectMonths, axis=1)
out.index = df.index
out.columns=["Month 0","Month 1","Month 2","Month 3"]

那么你得到的输出是:

代码语言:javascript
运行
复制
>>> out
         Month 0  Month 1  Month 2  Month 3
Account                                    
1            218      199      231      173
2            174      209      206      196
3            175      178      165      205
4            158      189      167      233
5            223      204      212      234
6            200      204      204      225
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63475520

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档