问题描述
input file contains the product and its price on a particular date
product 05-Oct-2020 07-Oct-2020 09-Nov-2020 13-Nov-2020
A 66.2 69.5 72.95 76.55
B 368.7 382.8 384.7 386.8
product Oct-2020 Nov-2020
A 66.2,69.5 72.95,76.55
B 368.7,382.8 384.7,386.8
我尝试将列名更改为日期格式,从“1-jan-2020”更改为“jan-2020” 与
keys = [dt.strptime(key,"%d-%b-%Y").strftime("%B-%Y") for key in data.keys()]
在df转置之后我们可以使用groupby。
就像有选项可以分组并将值相加为:-
df.groupby().sum()
有什么东西可以连接值(字符串操作)并用逗号分隔它们。
感谢任何方向。
解决方法
诀窍是在列上使用 Grouper:
inp = pd.read_excel("Stackoverflow sample.xlsx")
df = inp.set_index("Product")
df.columns = pd.to_datetime(df.columns)
out = (
df
.T
.groupby(pd.Grouper(level=0,freq="MS"))
.agg(lambda xs: ",".join(map(str,filter(pd.notnull,xs))))
.T
)
如果要转换为特定日期格式,请执行
out.columns = out.columns.strftime("%b-%Y")