将 DatetimeIndex 扩展到 Python pandas 中的行
Expanding DatetimeIndex to rows in Python pandas
我有一个 pandas 数据框,其中包含 3 列 DateIndex、Country 和 Awareness
我需要将 DateIndex 转换为每行的单独日期条目。
输入:
国家意识日期索引
美国 50% DatetimeIndex(['2017-05-01', '2017-05-02', '20...
英国 75% DatetimeIndex(['2018-05-01', '2018-05-02', '20...
输出:
国家意识日期
美国 50% 2017-05-01
美国 50% 2017-05-02
.
.
英国 75% 2018-05-01
英国 75% 2018-05-02
pandas 0.25+ DataFrame.explode
的解决方案:
df = pd.DataFrame({'Country':['USA','UK'],
'Awareness':['50%','75%'],
'Datetime':[pd.date_range('2017-05-01','2017-05-03'),
pd.date_range('2017-05-01','2017-05-04')]})
df = df.explode('Datetime')
print (df)
Country Awareness Datetime
0 USA 50% 2017-05-01
0 USA 50% 2017-05-02
0 USA 50% 2017-05-03
1 UK 75% 2017-05-01
1 UK 75% 2017-05-02
1 UK 75% 2017-05-03
1 UK 75% 2017-05-04
我有一个 pandas 数据框,其中包含 3 列 DateIndex、Country 和 Awareness
我需要将 DateIndex 转换为每行的单独日期条目。
输入:
国家意识日期索引
美国 50% DatetimeIndex(['2017-05-01', '2017-05-02', '20...
英国 75% DatetimeIndex(['2018-05-01', '2018-05-02', '20...
输出:
国家意识日期
美国 50% 2017-05-01
美国 50% 2017-05-02
.
.
英国 75% 2018-05-01
英国 75% 2018-05-02
pandas 0.25+ DataFrame.explode
的解决方案:
df = pd.DataFrame({'Country':['USA','UK'],
'Awareness':['50%','75%'],
'Datetime':[pd.date_range('2017-05-01','2017-05-03'),
pd.date_range('2017-05-01','2017-05-04')]})
df = df.explode('Datetime')
print (df)
Country Awareness Datetime
0 USA 50% 2017-05-01
0 USA 50% 2017-05-02
0 USA 50% 2017-05-03
1 UK 75% 2017-05-01
1 UK 75% 2017-05-02
1 UK 75% 2017-05-03
1 UK 75% 2017-05-04