Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将文本日期转换为年份+;分拣月份(即2019年1月19日至201901年)_Python_Sql_Pandas - Fatal编程技术网

Python 将文本日期转换为年份+;分拣月份(即2019年1月19日至201901年)

Python 将文本日期转换为年份+;分拣月份(即2019年1月19日至201901年),python,sql,pandas,Python,Sql,Pandas,在我的sql数据库(tests.db)表(triangle)中有一个名为paiddate的列。例如,它是一个类似于'1/19/2019'的文本字段。在另一个名为paidmonth的专栏中,我需要类似于'201901'的内容,它允许我按年份和月份对数据进行排序。我试过了- def getYearMonth(s): return s.split("/")[0]+"-"+s.split("/")[2] 这给了我1-2019年的时间,看起来还行,但没有按日期排序。它按数字排序。因此,1-2019

在我的sql数据库(tests.db)表(triangle)中有一个名为paiddate的列。例如,它是一个类似于
'1/19/2019'
的文本字段。在另一个名为paidmonth的专栏中,我需要类似于
'201901'
的内容,它允许我按年份和月份对数据进行排序。我试过了-

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


这给了我1-2019年的时间,看起来还行,但没有按日期排序。它按数字排序。因此,1-2019将在1-2018之后出现,而不是12-2018。

您可以使用pandas将字符串date-time转换为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:

好的,如果您只想创建一个单独的列,即year-month,您可以首先将字符串转换为日期(如第一个答案中所示),然后使用.dt.period()将该日期设置为year-month

保留完整日期有一些优点,因为您可以使用pandas times series(按日期时间索引的数据帧)方法按月(或季度、日或年…)分组,并对时间序列执行任何类型的聚合,甚至滚动函数。下面的示例按月对付款列求和

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())

参考:

pandas.to\u datetime
dt.strftime
一起使用:

import pandas as pd

df = pd.DataFrame()
df['col1'] = ['%s/19/2019' % i for i in range(1, 10)]
df['col2'] = pd.to_datetime(df['col1']).dt.strftime('%Y%m')
print(df)
样本数据:

        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\u datetime

import pandas as pd

df = pd.DataFrame()
df['col1'] = ['%s/19/2019' % i for i in range(1, 10)]
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

格式为“yyyymm”的字符串也是如此。将字符串转换为相应的日期(使用strftime)并使用日期,或者您可以将这些日期转换为整数并用它们填充数据框。
d.split('/')[2]+格式(int(d.split('/')[0]),'02d')
就是这样做的,谢谢!这似乎转换为包括天在内的日期。我需要按月份对数据进行分组,因此我只希望按日期对201902或02-2019进行排序