Reputation: 616
Say we have a dictionary like this: dic = {"2019-01" : "0.3", "2019-02": "0.4", "2019-03": "0.5"}
and a dataframe like this:
ID Date Volume Sales
0 1 2019-01 3.333333 1.333333
1 1 2019-01 3.333333 1.333333
2 1 2019-01 3.333333 1.333333
3 1 2019-02 2.666667 2.000000
4 1 2019-02 2.666667 2.000000
5 1 2019-02 2.666667 2.000000
6 1 2019-03 2.000000 2.666667
7 1 2019-03 2.000000 2.666667
8 1 2019-03 2.000000 2.666667
9 2 2019-01 1.333333 3.333333
10 2 2019-01 1.333333 3.333333
11 2 2019-01 1.333333 3.333333
Is there a way to create a column which matches the dictionary to the dataframe "Date" column
Output would look like:
ID Date Volume Sales dic
0 1 2019-01 3.333 1.333 0.3
1 1 2019-01 3.333 1.333 0.3
2 1 2019-01 3.333 1.333 0.3
3 1 2019-02 2.667 2.000 0.4
4 1 2019-02 2.667 2.000 0.4
5 1 2019-02 2.667 2.000 0.4
6 1 2019-03 2.000 2.667 0.5
7 1 2019-03 2.000 2.667 0.5
8 1 2019-03 2.000 2.667 0.5
9 2 2019-01 1.333 3.333 0.3
10 2 2019-01 1.333 3.333 0.3
11 2 2019-01 1.333 3.333 0.3
Upvotes: 1
Views: 59
Reputation: 195438
Use .map()
:
dic = {"2019-01": "0.3", "2019-02": "0.4", "2019-03": "0.5"}
df["dic"] = df["Date"].map(dic)
print(df)
Prints:
ID Date Volume Sales dic
0 1 2019-01 3.333333 1.333333 0.3
1 1 2019-01 3.333333 1.333333 0.3
2 1 2019-01 3.333333 1.333333 0.3
3 1 2019-02 2.666667 2.000000 0.4
4 1 2019-02 2.666667 2.000000 0.4
5 1 2019-02 2.666667 2.000000 0.4
6 1 2019-03 2.000000 2.666667 0.5
7 1 2019-03 2.000000 2.666667 0.5
8 1 2019-03 2.000000 2.666667 0.5
9 2 2019-01 1.333333 3.333333 0.3
10 2 2019-01 1.333333 3.333333 0.3
11 2 2019-01 1.333333 3.333333 0.3
Upvotes: 3