[英]pd.to_datetime doesn't respect the format
我有以下數據框:
month value
0 1949-01 3
1 1949-02 4
2 1949-03 5
df['month'] = pd.to_datetime(df['month'], format= '%Y/%m')
我想以以下格式獲取月份:
1949/01
但是輸出總是這樣:
month value
0 1949-01-01 3
1 1949-02-01 4
2 1949-03-01 5
為什么它會自動添加日期而不遵守格式?
這就是熊貓日期時間的格式。 如果需要,可以使用dt.strftime
轉換該日期時間格式
df['month'] = df['month'].dt.strftime('%Y/%m')
或者,您可以采用更簡單的方法開始並僅使用映射功能,而無需涉及日期時間格式
df['month'] = df['month'].map(lambda x: x.replace('-', '/'))
我認為您在混淆信息的存儲方式(“ dtype”)以及如何向您顯示信息。 下面的示例代碼說明了這一點:
import pandas as pd
# create sample dataframe where month is a string
df = pd.DataFrame({'month_str':['1949-01', '1949-02', '1949-03']})
# now create a new column where you have converted the string to a datetime
df['month_datetime'] = pd.to_datetime(df['month_str'])
# now convert the datetime back to a string with your desired format
df['month_new_str'] = df['month_datetime'].dt.strftime('%Y/%m')
# skip all the fooling around with datetimes and just manipulate it as a string directly
df['month_new_str2'] = df['month_str'].apply(lambda x: x.replace('-', '/'))
print(df.dtypes)
print(df)
結果為以下輸出:
month_str object
month_datetime datetime64[ns]
month_new_str object
month_new_str2 object
dtype: object
month_str month_datetime month_new_str month_new_str2
0 1949-01 1949-01-01 1949/01 1949/01
1 1949-02 1949-02-01 1949/02 1949/02
2 1949-03 1949-03-01 1949/03 1949/03
請注意,原始的“ month_str”列具有dtype對象(它是字符串)。 當您調用to_datetime時,我們將其轉換為datetime類型(無需指定格式,pandas會指出)。 但是,當顯示時,pandas會將其顯示為完整日期(這就是為什么您看到“日期”字段的原因)。 正如@sds指出的那樣,如果您只想將破折號切換為斜杠,則可以操縱原始字符串以產生新的字符串('month_new_str2')。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.