使用熊猫更改列数据类型

时间:2020-04-11 14:17:23

标签: python excel pandas datetime

我有一个带有日期列的数据框。该列包括“自定义”和“常规”数据类型。我想更改所有日期时间格式。 “ 43891”表示“ 01.03.2020 00:00:00”

TARİH
28.02.2020  00:00:00 -->custom
28.02.2020  00:00:00 -->custom
28.02.2020  00:00:00 -->custom
43891 -->general
43891 -->general
43891 -->general
.
.

这是我在下面尝试过的问题,与我同样存在问题(参考changing all dates to standard date time in dataframe

import pandas as pd
from datetime import datetime, timedelta

def from_excel_ordinal(ordinal, _epoch0=datetime(1899, 12, 31)):
    if ordinal >= 60:
        ordinal -= 1  # Excel leap year bug, 1900 is not a leap year!
    return (_epoch0 + timedelta(days=ordinal)).replace(microsecond=0)

df = pd.read_excel('D:\Documents\Desktop\deneme/deneme1.xlsx', sheet_name='Sheet1')
m = df['TARİH'].astype(str).str.isdigit()

df.loc[m, 'TARİH'] = \
df.loc[m, 'TARİH']\
  .astype(int)\
  .apply(from_excel_ordinal)

df['TARİH'] = pd.to_datetime(df['TARİH'], errors='coerce')

df.to_excel('D:\Documents\Desktop\deneme/deneme1.xlsx',index=False)

应用这些代码时,我在下面共享输出。 “常规类型”单元格变为“ NaT”。

print(df.loc[3280:3286, 'TARİH'])

Output: 
2020-02-28
2020-02-28
2020-02-28
2020-02-28
NaT
NaT
NaT
Name: TARİH, dtype: datetime64[ns]

在此解决方案中,changing all dates to standard date time in dataframe所有列均为“常规”数据类型。由于这个问题得以解决。但是,当我将上述代码应用于数据框时,列D格式变为“日期时间”格式。因此,我第二次运行代码时遇到以下错误:

TypeError: cannot astype a datetimelike from [datetime64[ns]] to [int32]

我每天都会使用这些代码。因此,我需要解决格式单元格问题。如果您愿意,我也可以尝试其他方法。

我也有3000行。因此,我无法应用手动方法。

2 个答案:

答案 0 :(得分:1)

IIUC,43891是自零日期以来的天数:

# zero_date = 1899-12-29
zero_date = pd.to_datetime('2020-03-01') - pd.to_timedelta(43891, unit='D')

然后您可以执行np.select

# you need dayfist
custom = pd.to_datetime(df['TARİH'], dayfirst=True, errors='coerce')

# general type
df['TARİH'] = np.where(custom.isna(), df['TARİH'],
                       (custom - zero_date)/pd.to_timedelta('1D')
                      )

答案 1 :(得分:0)

用熊猫方法没有任何疑问。因此,我使用了“ pynput.mouse”库。

当使用鼠标控制器方法将列样式更改为“短日期”时, df ['TARİH'] = pd.to_datetime(df ['TARİH'])没有混合的日期时间和整数传递的数组,整列具有相同的格式。

如果您使用熊猫或其他任何方法,请回答。

from pynput.mouse import Button, Controller
import pandas as pd

#Go to desktop
mouse= Controller ()
mouse.move(1358,751)
mouse.click(Button.left, 1)

#Open folder
mouse.position=(632, 108)
time.sleep(2)
mouse.click(Button.left,2)

#Open excel file
mouse.position=(354, 127)
time.sleep(2)
mouse.click(Button.left,2)

#Select D column in excel
mouse.position=(250, 256)
time.sleep(10)
mouse.click(Button.left,1)

#Go to format cell area
mouse.position=(709, 87)
time.sleep(2)
mouse.click(Button.left,1)

#Change format to short date
mouse.position=(663, 297)
time.sleep(2)
mouse.click(Button.left,1)

#Close excel file
mouse.position=(1337, 11)
time.sleep(2)
mouse.click(Button.left,1)

#Save excel file
mouse.position=(597, 400)
time.sleep(2)
mouse.click(Button.left,1)

#wait till excel close
time.sleep(3)

print("Formula writing operation is starting..")
df = pd.read_excel('D:\Documents\Desktop\deneme/2020 Data_çalışma.xlsx', sheet_name='Sheet1')
df['TARİH'] = pd.to_datetime(df['TARİH'])
print("Formula is written..")


Output:
TARİH
28.02.2020  00:00:00
28.02.2020  00:00:00
28.02.2020  00:00:00
01.03.2020  00:00:00
01.03.2020  00:00:00
01.03.2020  00:00:00
.
.