I have a dataframe like so:
Date Value
19990506 0.6
19990506 0.8
19990607 1.2
20000802 0.4
and I also have two lists like this:
list1 = ['19990506', '19990607', '20000802']
list2 = ['1999201', '1999232', '2000252']
the items in list1
coincide with the values in the column Date
and I want to replace them with the items that are in list2
. So in Date
19990506
is replaced with 1999201
and 19990607
is replaced with 1999232
. I think I need to zip my lists to do this, but after that I am at a loss on the best way to go about it. I am showing a very simplified dataframe so simply using .replace
is not efficient for me. My desired output is this:
Date Value
1999201 0.6
1999201 0.8
1999232 1.2
2000252 0.4
If you create a dictionary that maps from list1
to list2
then you can use Series.map
:
df = pd.read_clipboard()
list1 = ['19990506', '19990607', '20000802']
list2 = ['1999201', '1999232', '2000252']
# When I read in your data I get ints in the Date column
# so I need ints in the replacement map, if you have
# strings then remove the int() conversions
replacement_map = {int(i1): int(i2) for i1, i2 in zip(list1, list2)}
df['Date'] = df['Date'].map(replacement_map)
df
Out[13]:
Date Value
0 1999201 0.6
1 1999201 0.8
2 1999232 1.2
3 2000252 0.4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With