2 回答

TA貢獻1943條經驗 獲得超7個贊
您可以使用 pandas 將字符串日期時間轉換為 datetime64 類型。它足夠聰明,可以通過檢查字符串來推斷格式(月優先或日優先)。您可以為其提供一個格式化程序,它可以加速它,這是一個非常大的數據集的限制器。
import pandas as pd
# Make some unsorted dates as strings in a dataframe
df = pd.DataFrame({
'dates': ['1/19/2019', '1/12/2019', '12/1/2019', '6/7/2019', '7/6/2019']
})
# create a new column that converts the string to a datetime64
df['paidmonth'] = pd.to_datetime(df['dates'])
# sort the data
df.sort_values('paidmonth', inplace=True)
df
答案 2:
好的,如果您只想創建一個單獨的年月列,您可以先將字符串轉換為日期(如第一個答案),然后使用 .dt.period() 將該日期設為年月.
保留完整日期有一些優點,因為您可以使用 pandas 時間序列(按日期時間索引的數據框)方法按月(或季度、日或年...)分組并進行任何類型的聚合,或者甚至是時間序列上的滾動函數。下面的示例按月匯總付款列。
import pandas as pd
import numpy as np
n=400
df = pd.DataFrame({
'Date': pd.date_range('2018-01-01', periods=n, freq='d'),
'Payment': np.random.randint(20, 500, n)
})
# Make a column that is only the year and month
df['year-month'] = ts['Date'].dt.to_period('M')
display(df.head())
# use the full date column to group by month ans sum the payments
df_bymonth = df.set_index('Date').resample('m').apply({'Payment': 'sum'})
display(df_bymonth.head())

TA貢獻1998條經驗 獲得超6個贊
pandas.to_datetime與 一起使用dt.strftime:
import pandas as pd
df = pd.DataFrame()
df['col1'] = ['%s/19/2019' % i for i in range(1, 10)]
樣本數據:
col1
0 1/19/2019
1 2/19/2019
2 3/19/2019
3 4/19/2019
4 5/19/2019
5 6/19/2019
6 7/19/2019
7 8/19/2019
8 9/19/2019
使用pd.to_datetime:
df['col2'] = pd.to_datetime(df['col1']).dt.strftime('%Y%m')
print(df)
輸出:
col1 col2
0 1/19/2019 201901
1 2/19/2019 201902
2 3/19/2019 201903
3 4/19/2019 201904
4 5/19/2019 201905
5 6/19/2019 201906
6 7/19/2019 201907
7 8/19/2019 201908
8 9/19/2019 201909
添加回答
舉報