I have a datetime format which am trying to use for one of my requirement. Here is my code and this is how the input dataframe looks like-
data=pd.DataFrame({'A': ['abc','bcd'], 'B': [pd.to_datetime('1/1/18 0:00'), 'apples'], 'C':[pd.to_datetime('1/2/18 0:00'),'mangoes'], 'D':[pd.to_datetime('1/3/18 0:00'),'orange'],'E':[pd.to_datetime('1/4/18 0:00'),'plantain'],
'F':[pd.to_datetime('1/5/18 0:00'),'plantain'],'G':[pd.to_datetime('1/6/18 0:00'),'red'],'H':[pd.to_datetime('1/2/18 0:00'),'green']})
(I have used pd.to_datetime to showcase the data format which I have in my input file)
My objective is to get the date to a str format which gives an o/p like- 1/18 (m/yy) instead of 1/1/18 (m-d-yy). I was trying this approach-
data.loc[0,['B']]='1-2018'
data.loc[0,['C']]='2-2018'
data.loc[0,['D']]='3-2018'
.
.
.
.
This would do my job but I need something which is more optimal and doesnt require me to write more line of codes. For eg- Say If the date were of 3-4 years of intervals, then using my approach it will be to tedious to write all the month and year.
Is there a better approach to use say a for loop for writing the above line of code?
CodePudding user response:
a way to make your dataframe a little bit more accessible might be to transpose it so you have an actual date column:
df_new = df.drop(columns=['A']).T.copy()
df_new.rename(columns={0: 'Date', 1: 'Fruit'}, inplace=True)
df_new['Date_str'] = df_new['Date'].dt.strftime('%m/%Y')
this will give you a date column with strings like '01/2018' also the table will be vertical basically.
if you need some other specifications please let me know :)