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
添加回答
举报