Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 分析熊猫中日期范围的字符串_Python_Datetime_Pandas_Date Range - Fatal编程技术网

Python 分析熊猫中日期范围的字符串

Python 分析熊猫中日期范围的字符串,python,datetime,pandas,date-range,Python,Datetime,Pandas,Date Range,我有一个pandas数据框,其中日期范围值作为字符串,格式为“2014-10-16-2014-10-23”,我希望保留此列,但为开始和结束年份、月份和日期(例如开始日期、结束日期等)添加新列 使用Python是否有一种简洁的方法来实现这一点,理想情况下利用时间序列特性并在数据帧内工作?您可以使用该方法;首先是: >>> df date 0 2014-01-24 - 2014-08-23 1 2012-03-12 - 2013-04

我有一个
pandas
数据框,其中日期范围值作为字符串,格式为“2014-10-16-2014-10-23”,我希望保留此列,但为开始和结束年份、月份和日期(例如开始日期、结束日期等)添加新列

使用Python是否有一种简洁的方法来实现这一点,理想情况下利用时间序列特性并在数据帧内工作?

您可以使用该方法;首先是:

>>> df
                      date
0  2014-01-24 - 2014-08-23
1  2012-03-12 - 2013-04-03
2  2014-10-16 - 2014-10-23

[3 rows x 1 columns]
提取部分可通过以下方式完成:

>>> cols = pd.MultiIndex.from_tuples([(x, y) for x in ['start', 'end'] for y in ['year', 'mon', 'day']])
>>> pat = r'(\d*)-(\d*)-(\d*) - (\d*)-(\d*)-(\d*)'
>>> xdf = pd.DataFrame(df.date.str.extract(pat).values, columns=cols, dtype=np.int64)
>>> xdf
   start             end          
    year  mon  day  year  mon  day
0   2014    1   24  2014    8   23
1   2012    3   12  2013    4    3
2   2014   10   16  2014   10   23

[3 rows x 6 columns]
如果要与原始数据帧连接:

>>> pd.concat([df, xdf], axis=1)

编辑:似乎更适合:

>>> pd.DataFrame(df.date.str.findall('\d+').tolist(), dtype=np.int64, columns=cols)
   start             end          
    year  mon  day  year  mon  day
0   2014    1   24  2014    8   23
1   2012    3   12  2013    4    3
2   2014   10   16  2014   10   23

[3 rows x 6 columns]
你可以使用这个方法;首先是:

>>> df
                      date
0  2014-01-24 - 2014-08-23
1  2012-03-12 - 2013-04-03
2  2014-10-16 - 2014-10-23

[3 rows x 1 columns]
提取部分可通过以下方式完成:

>>> cols = pd.MultiIndex.from_tuples([(x, y) for x in ['start', 'end'] for y in ['year', 'mon', 'day']])
>>> pat = r'(\d*)-(\d*)-(\d*) - (\d*)-(\d*)-(\d*)'
>>> xdf = pd.DataFrame(df.date.str.extract(pat).values, columns=cols, dtype=np.int64)
>>> xdf
   start             end          
    year  mon  day  year  mon  day
0   2014    1   24  2014    8   23
1   2012    3   12  2013    4    3
2   2014   10   16  2014   10   23

[3 rows x 6 columns]
如果要与原始数据帧连接:

>>> pd.concat([df, xdf], axis=1)

编辑:似乎更适合:

>>> pd.DataFrame(df.date.str.findall('\d+').tolist(), dtype=np.int64, columns=cols)
   start             end          
    year  mon  day  year  mon  day
0   2014    1   24  2014    8   23
1   2012    3   12  2013    4    3
2   2014   10   16  2014   10   23

[3 rows x 6 columns]