【问题标题】:problems with python Pandas converting int to floatpython Pandas将int转换为float的问题
【发布时间】:2020-11-06 19:17:41
【问题描述】:

我正在使用 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"

谁能解释这里发生了什么并帮我解决它?

【问题讨论】:

  • 使用此方法检查数据框中每一列的数据类型 pandas.DataFrame.dtypes 可能“workshop Month”是浮点数,如果您插入一个 int 值,它会将其转换为浮点数
  • 'workshop Month' 是类型系列。创建它的 eMonths 对象是一个列表。进入列表的各个 eMonth 对象是 int 类型。然而,当将“workshop Month”放入 df 列时,它看起来像一个浮点数。

标签: python python-3.x pandas


【解决方案1】:

解决方案

要将您的日期列转换(重新格式化)为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)

【讨论】:

  • @NWWPA 这能解决问题吗?如果您有任何问题,请告诉我。
  • 感谢您的努力。您在 A 部分的解决方案解决了其中一个问题,但不是全部。 eHomeHBEdata 'course session' 值是固定的,但 eHomeHBEdata['start'] 仍然需要 for 循环提取的月份和日期数值。例如并且输入日期“2020 年 11 月 5 日”将为“开始”创建一个“2020 年 11 月 1 日”的输出值。原因与我将加载输出 CSV 的 CRM 软件有关。
  • @NWWPA 您能否分享“输入数据”和“预期输出数据”作为样本?现在我不清楚你到底在找什么。
  • 在上面的 for 循环之后,eMonths 和 eYears 列表中的对象是 int 类型。在将它们分配给列之后,它们以某种方式转换为浮点类型:eHomeHBEdata.insert(0,'workshop Month',eMonths) eHomeHBEdata.insert(1,'workshop Year',eYears) 我得到“10.0”而不是“10”和“2020.0”而不是“2020”
  • @NWWPA 请检查我的解决方案中的Section-C
猜你喜欢
  • 1970-01-01
  • 2021-11-02
  • 2017-03-08
  • 2016-07-19
  • 1970-01-01
  • 1970-01-01
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多