Adding yearly Inflation column according to DateTime column

Question:

Here is my DateTime column on a dataframe I want to add two different columns like ‘Yearly Inflation Rate of UK’ and ‘Yearly Inflation Rate of Turkey’ according the ‘year’ on DateTime Column. I need your help how to do it on python

INPUT:

| DateTime |
|14.08.2014|  
|15.07.2015| 
|16.06.2016|

Desired Output:

DateTime Inflation of UK Inflation of Turkey
14.08.2014 2.36 8.85
15.07.2015 0.37 7.67
16.06.2016 1.01 7.78
Asked By: Orhan Dağ

||

Answers:

Example

data = {' DateTime ': {0: '14.08.2014', 1: '15.07.2015', 2: '16.06.2016'}}
df = pd.DataFrame(data)

df

    DateTime
0   14.08.2014
1   15.07.2015
2   16.06.2016

Code

out = df.assign(Inflation_of_UK=[2.36, 0.37, 1.01], Inflation_of_Turkey=[8.85, 7.67, 7.78])

out

    DateTime    Inflation_of_UK Inflation_of_Turkey
0   14.08.2014  2.36            8.85
1   15.07.2015  0.37            7.67
2   16.06.2016  1.01            7.78
Answered By: Panda Kim

Try this

df['Year'] = pd.DatetimeIndex(df['DateTime'). 
df = df.merge(inflation_rates, left_on='Year', right_on='Year', how='left')
df.rename(columns={'UK_Inflation_Rate': 'Inflation of UK', 'Turkey_Inflation_Rate': 'Inflation of Turkey'}, inplace=True)
df.drop('Year', axis=1, inplace=True)
print(df)
Answered By: apan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.