数据格式化熊猫

时间:2018-11-22 20:28:39

标签: python pandas datetime

我正在尝试输入一行代码来为索引31'st January 1995创建一行。我无法使行看起来像31/01/1995,而输出是1995-01-31 00:00:00

我在名为MainData的数据框中的原始数据

我试图在1995年1月31日的顶部添加一行,格式与以下数据相同。

enter image description here

我的代码是

MainData.loc[pd.to_datetime('31/01/1995',format='%d/%m/%Y'),:] = [100 for number in range(7)]
MainData

enter image description here

请告诉我是否有办法将其重新格式化为31/01/1995

谢谢。

1 个答案:

答案 0 :(得分:0)

#Making the data look more normal by removing the first column index level
MainData = MainData.rename(columns=MainData.iloc[0])
MainData = MainData.iloc[1:]
#Re-adjusting the Index to a datetime format
MainData['DateAdjusted'] = MainData.index
MainData = MainData.reset_index(drop=True)
MainData['DateAdjusted'] = pd.to_datetime(MainData['DateAdjusted'],dayfirst=True)

#Just renaming the Column and converting the index back to Date
MainData.rename(columns={'DateAdjusted':'Date'},inplace=True)
MainData.index = MainData['Date']
del MainData['Date']

#Defining the date for the row I want to add
InitialDate = "31/01/1995"
format_str = '%d/%m/%Y' 
datetime_obj = datetime.datetime.strptime(InitialDate, format_str)
print (datetime_obj.date())

MainData.loc[datetime_obj,:] = [100 for number in range(7)]
MainData = MainData.sort_index(ascending=True)