簡體   English   中英

python Pandas 將 int 轉換為 float 的問題

[英]problems with python Pandas converting int to float

我正在使用 pandas read_csv 來提取數據並重新格式化。 例如,“HBE 日期”列中的“10/28/2018”將被重新格式化為“eHome 10/2018”

除了我得到像“ehome 1.0/2015.0”這樣的重新格式化的值外,它大部分都有效

eHomeHBEdata['HBE date'] = pd.to_datetime(eHomeHBEdata['Course Completed'])

#extract month and year values
eMonths=[]
eYears =[]
eHomeDates = eHomeHBEdata['HBE date']

for eDate in eHomeDates:
        eMonth = eDate.month
        eYear = eDate.year
        eMonths.append(eMonth)
        eYears.append(eYear)

此時,如果我 print(type(eMonth)) 它返回為“int”。 如果我打印 eYears 列表,我會得到 2013、2014、2015 等值。

但隨后我將列表分配給數據框中的列。 . .

eHomeHBEdata.insert(0,'workshop Month',eMonths)
eHomeHBEdata.insert(1,'workshop Year',eYears)

. . . 之后 print(ehomeHomeHBEdata['workshop Month']) 返回值,如 2013.0、2014.0、2015.0。 那是浮動類型,對吧?

當我嘗試使用以下代碼時,出現上述格式錯誤的錯誤

eHomeHBEdata['course session'] = "ehome " + eHomeHBEdata['workshop Month'].astype(str) + "/" + eHomeHBEdata['workshop Year'].astype(str)
eHomeHBEdata['start'] = eHomeHBEdata['workshop Month'].astype(str) + "/1/" + eHomeHBEdata['workshop Year'].astype(str) + " 12:00 PM"

有人可以解釋這里發生了什么並幫助我解決它嗎?

解決方案

要將日期列轉換(重新格式化)為MM/YYYY ,您需要做的就是:

df["Your_Column_Name"].dt.strftime('%m/%Y')

有關兩個不同的用例,請參閱Section-ASection-B

A. 示例

我為此插圖創建了一些虛擬數據,其中有一列名為: Date 將此列重新格式化為MM/YYYY我使用df.Dates.dt.strftime('%m/%Y')相當於df["Dates"].dt.strftime('%m/%Y') .

import pandas as pd

## Dummy Data
dates = pd.date_range(start='2020/07/01', end='2020/07/07', freq='D')
df = pd.DataFrame(dates, columns=['Dates'])

# Solution
df['Reformatted_Dates'] = df.Dates.dt.strftime('%m/%Y')
print(df)
## Output:
#        Dates Reformatted_Dates
# 0 2020-07-01           07/2020
# 1 2020-07-02           07/2020
# 2 2020-07-03           07/2020
# 3 2020-07-04           07/2020
# 4 2020-07-05           07/2020
# 5 2020-07-06           07/2020
# 6 2020-07-07           07/2020

B.如果你輸入的數據是以下格式

在這種情況下,首先您可以在列上使用.astype('datetime64[ns, US/Eastern]')轉換日期。 這使您可以在列上應用 Pandas 日期時間特定方法。 現在嘗試運行df.Dates.astype('datetime64[ns, US/Eastern]').dt.to_period(freq='M')

## Dummy Data
dates = [
    '10/2018', 
    '11/2018', 
    '8/2019', 
    '5/2020',
]

df = pd.DataFrame(dates, columns=['Dates'])
print(df.Dates.dtype)
print(df)

## To convert the column to datetime and reformat
df['Dates'] = df.Dates.astype('datetime64[ns, US/Eastern]') #.dt.strftime('%m/%Y')
print(df.Dates.dtype)

C. 避免使用for loop

嘗試這個。 您可以在列上使用 Pandas 的內置矢量化,而不是在每一行上循環。 我在列上使用.dt.month.dt.year將月份和年份作為int

eHomeHBEdata['HBE date'] = pd.to_datetime(eHomeHBEdata['Course Completed'])
eHomeDates = eHomeHBEdata['HBE date'] # this should be in datetime.datetime format

## This is what I changed
>>> eMonths = eHomeDates.dt.month
>>> eYears = eHomeDates.dt.year

eHomeHBEdata.insert(0,'workshop Month',eMonths)
eHomeHBEdata.insert(1,'workshop Year',eYears)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM