PythonPandas:Pandas。到目前为止()当日不到13时是否切换日和月

2024-04-19 18:50:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个可以读取多个文件的代码,但是在我的一些文件中,只要日期小于13天,并且从第13天或以上的任何一天(即2011年6月13日)都保持正确(DD/MM/YY)。 我试着通过这样做来修复它,但是不起作用。在

我的数据框如下所示: 实际日期时间为2015年6月12日至2015年6月13日 当我将日期时间列作为字符串读取时,日期保持正确的dd/mm/yyyy

tmp                     p1 p2 
11/06/2015 00:56:55.060  0  1
11/06/2015 04:16:38.060  0  1
12/06/2015 16:13:30.060  0  1
12/06/2015 21:24:03.060  0  1
13/06/2015 02:31:44.060  0  1
13/06/2015 02:37:49.060  0  1

但是当我将我的列类型更改为datetime列时,它会将我的日期和月份替换为少于13天的每一天。在

输出:

^{pr2}$

这是我的代码:

我循环浏览文件:

df = pd.read_csv(PATH+file, header = None,error_bad_lines=False , sep = '\t')

然后,当我的代码读取完所有连接它们的文件时,问题是我的datetime列需要在datetime类型中,所以当我通过pd_datetime()更改它的类型时,它会在日期小于13时交换日期和月份。在

转换我的日期时间列后日期正确(字符串类型)

print(tmp) # as a result I get 11.06.2015 12:56:05 (11june2015)

但当我改变列类型时,我得到的是:

tmp = pd.to_datetime(tmp, unit = "ns")
tmp = temps_absolu.apply(lambda x: x.replace(microsecond=0))
print(tmp) # I get 06-11-2016 12:56:05 (06november2015 its not the right date)

问题是:当日小于13时,我应该使用或更改什么命令来停止日月交换?在

更新 这个命令可以交换我专栏的所有日期和月份

tmp =  pd.to_datetime(tmp, unit='s').dt.strftime('%#m/%#d/%Y %H:%M:%S') 

所以为了只交换不正确的日期,我写了一个条件:

for t in tmp:
        if (t.day < 13):
            t = datetime(year=t.year, month=t.day, day=t.month, hour=t.hour, minute=t.minute, second = t.second)

但也不管用


Tags: 文件to字符串代码命令类型getdatetime
2条回答

好吧,我解决了我的问题,但在一个消耗内存的方法中,我首先将tmp列拆分为日期和时间列,然后将日期列重新拆分为day month和year,这样我就可以查找小于13的日期,并用相应的月份替换它们

df['tmp'] = pd.to_datetime(df['tmp'], unit='ns')
df['tmp'] = df['tmp'].apply(lambda x: x.replace(microsecond=0))
df['date'] = [d.date() for d in df['tmp']]
df['time'] = [d.time() for d in df['tmp']]
df[['year','month','day']] = df['date'].apply(lambda x: pd.Series(x.strftime("%Y-%m-%d").split("-")))

df['day'] = pd.to_numeric(df['day'], errors='coerce')
df['month'] = pd.to_numeric(df['month'], errors='coerce')
df['year'] = pd.to_numeric(df['year'], errors='coerce')


#Loop to look for days less than 13 and then swap the day and month
for index, d in enumerate(df['day']):
        if(d <13): 
 df.loc[index,'day'],df.loc[index,'month']=df.loc[index,'month'],df.loc[index,'day'] 

#将序列转换为字符串类型以合并它们

^{pr2}$

#在我们的列中合并时间、日期和地点结果

df['tmp'] =pd.to_datetime(df['date']+ ' '+df['time'])

#删除添加的列

df.drop(df[['date','year', 'month', 'day','time']], axis=1, inplace = True)

您可以在pd.to_datetime中使用dayfirst参数。在

pd.to_datetime(df.tmp, dayfirst=True)

输出:

^{pr2}$

相关问题 更多 >