My df is like this
import pandas as pd
import numpy as np
df = pd.DataFrame({'Date data':['actual september 2019', 'September'],
'Date':['2019.12','2019.12']})
I would like to create a new columne and if df['Date data']
is 'September'
I would like to write df['new_column'] = '2019.09'
the expected output is
import pandas as pd
import numpy as np
df = pd.DataFrame({'Date data':['actual september 2019', 'September'],
'Date':['2019.12','2019.12'], 'New_column':['2019.12','2019.09']})
i created a variable
month = ('April', 'December', 'February', 'January', 'July-August', 'June', 'March', 'May', 'November', ' October', 'September')
and
df.loc[df['Date data'].isin(month) , 'new_col'] = '2019.9
CodePudding user response:
IIUC, you want to create a new column similar to Date
. Rows where Date data
is equal to a month I change the column number in Date
and put it in the new column.
If all months start with a capital letter (easy):
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
df['New_column'] = df['Date']
for nr, month in enumerate(months):
df.loc[df['Date data'].eq(month), 'New_column'] = df['Date'].str[:5] str(nr 1).zfill(2)
If months can be with or without capital letter, use .lower()
:
months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
df['New_column'] = df['Date']
for nr, month in months:
df.loc[df['Date data'].str.lower().eq(month), 'New_column'] = df['Date'].str[:5] str(nr 1).zfill(2)
Output:
Date data Date New_column
0 actual september 2019 2019.12 2019.12
1 September 2019.12 2019.09
CodePudding user response:
IIUC, you can use:
from calendar import month_name
mapper = {m.lower(): f'{i:02d}' for i,m in enumerate(month_name)}
df['New_column'] = (df['Date data'].str.lower()
.map(mapper)
.radd('2019.')
.fillna(df['Date'])
)
example:
Date data Date New_column
0 actual september 2019 2019.12 2019.12
1 September 2019.12 2019.09
2 ApRil 2019.12 2019.04