'How to apply a dictionary across a row of a dataframe
Say I have a dictionary that the key of year, and the corresponding value of a list of values. Is there a way to apply that value across the row of a dataframe. For instance if my key is "1995" how do I apply element 1 of the dictionary to column 1, element 2 to column 2 and etc for the whole entire dictionary?
my dictionary is as follows:
my_dict = {'1995' : [.99,.98,.96],'1994' : [.9995,.986,.97]}
now I have a dataframe organized as such
df = pd.DataFrame({'issue year' : {1995,1994}
'legal entitiy': {'a',"a"}
'x': {100,98},
'y': {98,97},
'z':{95,80})
I wish to apply across each row such that for 1995 we hit 100 with .99,98 with .98 anda 95 with .96
1994 would get 98 with .995, 97 with .986 and so on. If there was a 3rd year column x y and z would have one more entry and each would get hit with a factor for that year.
pd.DataFrame({'issue year' : {1995,1994}
'legal entitiy': {'a',"a"}
'x': {100*.99, 98 * .9995},
'y': {98*.98, 97*.986},
'z':{95*.96, 80 * .97})
Solution 1:[1]
First you transform your dictionary into a Dataframe with the names of the columns you want to apply your operation on e.g.
df_1 = pd.DataFrame.from_dict(my_dict, orient='index',columns=['x','y','z'])
df_1.index = df_1.index.astype(int)
Then you can use slices to select the part of dataframe you want to perform the operation on and the use a standard arithmetic operator.
df = df.set_index('issue year')
df.loc[df_1.index,df_1.columns] = df.loc[df_1.index,df_1.columns]*df_1
df = df.reset_index()
Which will result in the desired dataframe
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
