用日期范围在列中扩展 pandas 数据框 [英] Expanding pandas data frame with date range in columns
本文介绍了用日期范围在列中扩展 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个熊猫数据框,其日期和字符串类似于此:
I have a pandas dataframe with dates and strings similar to this:
Start End Note Item
2016-10-22 2016-11-05 Z A
2017-02-11 2017-02-25 W B
我需要将其扩展/转换为以下内容,在开始和结束列之间填写几周(W-SAT),然后在注意和项目:
I need to expand/transform it to the below, filling in weeks (W-SAT) in between the Start and End columns and forward filling the data in Note and Items:
Start Note Item
2016-10-22 Z A
2016-10-29 Z A
2016-11-05 Z A
2017-02-11 W B
2017-02-18 W B
2017-02-25 W B
用熊猫做这件事的最好方法是什么?某种类型的多索引适用吗?
Whats the best way to do this with pandas? Some sort of multi-index apply?
推荐答案
您可以遍历每一行并创建一个新的数据框,然后将它们连接在一起
You can iterate over each row and create a new dataframe and then concatenate them together
pd.concat([pd.DataFrame({'Start': pd.date_range(row.Start, row.End, freq='W-SAT'),
'Note': row.Note,
'Item': row.Item}, columns=['Start', 'Note', 'Item'])
for i, row in df.iterrows()], ignore_index=True)
Start Note Item
0 2016-10-22 Z A
1 2016-10-29 Z A
2 2016-11-05 Z A
3 2017-02-11 W B
4 2017-02-18 W B
5 2017-02-25 W B
这篇关于用日期范围在列中扩展 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文