我使用pandas read_csv来提取数据并重新格式化。例如,"HBE date“列中的"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)此时,如果我打印(类型(EMonth)),它返回为‘it’。如果我打印eYears列表,我会得到2013、2014、2015等值。
然后,我将列表分配给数据框中的列。。。
eHomeHBEdata.insert(0,'workshop Month',eMonths)
eHomeHBEdata.insert(1,'workshop Year',eYears)。。。之后,print(ehomeHomeHBEdata‘研讨会月’)返回类似于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"有人能解释一下这是怎么回事并帮我解决吗?
发布于 2020-11-05 06:25:04
解决方案
要将日期列转换(重新格式化)为MM/YYYY,您只需执行以下操作:
df["Your_Column_Name"].dt.strftime('%m/%Y')有关两种不同的用例,请参阅部分-A和部分-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/2020B.如果您的输入数据采用以下格式
在本例中,首先可以使用列上的.astype('datetime64[ns, US/Eastern]')转换日期。这允许您在列上应用特定于pandas datetime的方法。现在尝试运行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)https://stackoverflow.com/questions/64688464
复制相似问题