簡體   English   中英

熊貓:如何計算日期欄中的年份月份?

[英]Pandas: how to take the year month of a date column?

我有一個大型數據框df ,其中包含日期的格式為%Y-%m-%d

df
    val     date
0   356   2017-01-03
1   27    2017-03-28
2   33    2017-07-12
3   455   2017-09-14

我想創建一個新列YearMonth ,其中包含%Y%m格式的日期

df['YearMonth'] = df['date'].dt.to_period('M')

但是要花很長時間

您的解決方案是更快strftime較大的DataFrame ,但有不同的輸出- Period s和strings

df['YearMonth'] = df['date'].dt.strftime('%Y-%m')
df['YearMonth1'] = df['date'].dt.to_period('M')
print (type(df.loc[0, 'YearMonth']))
<class 'str'>

print (type(df.loc[0, 'YearMonth1']))
<class 'pandas._libs.tslibs.period.Period'>

#[40000 rows x 2 columns]
df = pd.concat([df] * 10000, ignore_index=True)

In [63]: %timeit df['date'].dt.strftime('%Y-%m')
237 ms ± 1.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [64]: %timeit df['date'].dt.to_period('M')
57 ms ± 985 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

列表理解也很慢:

In [65]: %timeit df['new'] = [str(x)[:7] for x in df['date']]
209 ms ± 2.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

亞歷山大的另一個解決方案:

In [66]: %timeit df['date'].astype(str).str[:7]
236 ms ± 1.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

如果尚未將date列轉換為字符串,則可以將其截斷為年份和月份(即前七個字符)。

df['YearMonth'] = df['date'].astype(str).str[:7]
   val        date YearMonth
0  356  2017-01-03   2017-01
1   27  2017-03-28   2017-03
2   33  2017-07-12   2017-07
3  455  2017-09-14   2017-09

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM