here in Days section '2020-april-4' i want to change it like this 4-04-2020 that's mean date/month/year. how can i do it?
CodePudding user response:
Say you have a CSV called lab_cases.csv
with the following contents:
Day,Lab Test,Confirmed,Death Case
2020-April-04,434,9,2
2020-April-05,367,18,1
2020-April-06,468,35,3
You could read the file into a pandas.DataFrame
and then use pandas.Series.dt.strftime
:
>>> import pandas as pd
>>> df = pd.read_csv('lab_cases.csv')
>>> df
Day Lab Test Confirmed Death Case
0 2020-April-04 434 9 2
1 2020-April-05 367 18 1
2 2020-April-06 468 35 3
>>> df['Day'] = pd.to_datetime(df['Day'], infer_datetime_format=True)
>>> df
Day Lab Test Confirmed Death Case
0 2020-04-04 434 9 2
1 2020-04-05 367 18 1
2 2020-04-06 468 35 3
>>> df['Day'] = df['Day'].dt.strftime('%-d-%m-%Y')
>>> df
Day Lab Test Confirmed Death Case
0 4-04-2020 434 9 2
1 5-04-2020 367 18 1
2 6-04-2020 468 35 3
>>> df.to_csv('modified_lab_cases.csv', index=False)
modified_lab_cases.csv
:
Day,Lab Test,Confirmed,Death Case
4-04-2020,434,9,2
5-04-2020,367,18,1
6-04-2020,468,35,3
CodePudding user response:
You could simply use a datetime
module to do that.
Your current format is %Y-%B-%d
Your desired format is %-d-%m-%Y
Here is an example for a single variable:
from datetime import datetime
mydate = '2020-April-04'
# Convert "mydate" string to a datetime object
converted_mydate = datetime.strptime(mydate, '%Y-%B-%d')
# This will print a datetime object
print(converted_mydate)
>>> 2020-04-04 00:00:00
# Change formatting to your desired style (and convert it to a string)
changed_mydate = converted_mydate.strftime('%-d-%m-%Y')
# This will print a string of your desired formatted datetime
print(changed_mydate)
>>> 4-04-2020
You can apply this to your "Day" column in a DataFrame with df.apply
or any of your desired ways (I assume that you would know how to do that)