将文本日期转换为年+月进行排序(即 1/19/2019 到 201901)

我的 sql 数据库(tests.db)表(三角形)中有一个名为paiddate 的列。例如,它是一个看起来像的文本字段'1/19/2019'。在另一个名为paidmonth 的列中,我想要类似的东西'201901',这将允许我按年和月对数据进行排序。我试过 -

def getYearMonth(s):
  return s.split("/")[0]+"-"+s.split("/")[2]

df['paidmonth']= df['paiddate'].apply(lambda x: getYearMonth(x))

这给了我 1-2019,看起来不错,但没有按日期排序。它按数字排序。所以 1-2019 将在 1-2018 之后,而不是 12-2018 之后。


狐的传说
浏览 124回答 2
2回答

杨__羊羊

您可以使用 pandas 将字符串日期时间转换为 datetime64 类型。它足够聪明,可以通过检查字符串来推断格式(月优先或日优先)。您可以为其提供一个格式化程序,它可以加速它,这是一个非常大的数据集的限制器。import pandas as pd# Make some unsorted dates as strings in a dataframedf = 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 datetime64df['paidmonth'] = pd.to_datetime(df['dates'])# sort the datadf.sort_values('paidmonth', inplace=True)df答案 2:好的,如果您只想创建一个单独的年月列,您可以先将字符串转换为日期(如第一个答案),然后使用 .dt.period() 将该日期设为年月.保留完整日期有一些优点,因为您可以使用 pandas 时间序列(按日期时间索引的数据框)方法按月(或季度、日或年...)分组并进行任何类型的聚合,或者甚至是时间序列上的滚动函数。下面的示例按月汇总付款列。import pandas as pdimport numpy as npn=400df = 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 monthdf['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())

米琪卡哇伊

pandas.to_datetime与 一起使用dt.strftime:import pandas as pddf = pd.DataFrame()df['col1'] = ['%s/19/2019' % i for i in range(1, 10)]样本数据:        col10  1/19/20191  2/19/20192  3/19/20193  4/19/20194  5/19/20195  6/19/20196  7/19/20197  8/19/20198  9/19/2019使用pd.to_datetime:df['col2'] = pd.to_datetime(df['col1']).dt.strftime('%Y%m')print(df)输出:        col1    col20  1/19/2019  2019011  2/19/2019  2019022  3/19/2019  2019033  4/19/2019  2019044  5/19/2019  2019055  6/19/2019  2019066  7/19/2019  2019077  8/19/2019  2019088  9/19/2019  201909
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python