You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Python Pandas中将DatetimeIndex展开为单独行的实现方法

Solution to Explode DatetimeIndex into Individual Rows

Got it, this is a common task when dealing with nested iterable values in a DataFrame. Here's how you can easily split those DatetimeIndex entries into separate rows while keeping the Country and Awareness values aligned:

Step-by-Step Code

First, let's assume your original DataFrame is named df. We'll use Pandas' explode() method, which is perfect for expanding iterable columns into individual rows:

# Optional: Convert DatetimeIndex objects to lists for broader compatibility (works with older Pandas versions)
df['DateIndex'] = df['DateIndex'].apply(list)

# Explode the DateIndex column and rename it to 'Date'
result_df = df.explode('DateIndex').rename(columns={'DateIndex': 'Date'})

What This Does

  • The explode() method takes each element in the iterable (your DatetimeIndex, now a list) and creates a new row for it, copying the corresponding Country and Awareness values each time.
  • Renaming the column to 'Date' gives you the clean output format you're looking for.

Example Input/Output

Input DataFrame:

CountryAwarenessDateIndex
USA50%DatetimeIndex(['2017-05-01', '2017-05-02', ...])
UK75%DatetimeIndex(['2018-05-01', '2018-05-02', ...])

Output DataFrame:

CountryAwarenessDate
USA50%2017-05-01
USA50%2017-05-02
.........
UK75%2018-05-01
UK75%2018-05-02

Note for Newer Pandas Versions

If you're using Pandas 1.3.0 or later, you can skip converting the DatetimeIndex to a list—explode() directly supports DatetimeIndex objects. Just run:

result_df = df.explode('DateIndex').rename(columns={'DateIndex': 'Date'})

内容的提问来源于stack exchange,提问作者user2419259

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:44:20