Suppose that I have the following df
with empty strings in the Volatility expected
column:
Index Time Currency Volatility expected Event Actual Forecast Previous
0 02:00 GBP U.K. Construction Output (YoY) (Jan) 9.9% 9.2% 7.4%
1 02:00 GBP Construction Output (MoM) (Jan) 1.1% 0.5% 2.0%
2 02:00 GBP GDP (MoM) 0.8% 0.2% -0.2%
3 02:00 GBP GDP (YoY) 10.0% 9.3% 6.0%
And the following list of lists called volatility_list
:
volatility_list = [
['Low Volatility Expected'],
['Low Volatility Expected'],
['High Volatility Expected'],
['High Volatility Expected'],
]
How could I add volatility_list
values to Volatility expected
column from df
so it ends up like this?
Index Time Currency Volatility expected Event Actual Forecast Previous
0 02:00 GBP Low Volatility Expected U.K. Construction Output (YoY) (Jan) 9.9% 9.2% 7.4%
1 02:00 GBP Low Volatility Expected Construction Output (MoM) (Jan) 1.1% 0.5% 2.0%
2 02:00 GBP High Volatility Expected GDP (MoM) 0.8% 0.2% -0.2%
3 02:00 GBP High Volatility Expected GDP (YoY) 10.0% 9.3% 6.0%
CodePudding user response:
You can use a comprehension to extract the first and only element of each item in your list:
df['Volatility expected'] = [v[0] for v in volatility_list]
print(df)
# Output
Time Currency Volatility expected Event Actual Forecast Previous
0 02:00 GBP Low Volatility Expected U.K. Construction Output (YoY) (Jan) 9.9% 9.2% 7.4%
1 02:00 GBP Low Volatility Expected Construction Output (MoM) (Jan) 1.1% 0.5% 2.0%
2 02:00 GBP High Volatility Expected GDP (MoM) 0.8% 0.2% -0.2%
3 02:00 GBP High Volatility Expected GDP (YoY) 10.0% 9.3% 6.0%
CodePudding user response:
You could assign it and explode
:
df['Volatility expected'] = volatility_list
df = df.explode('Volatility expected')
Output:
Index Time Currency Volatility expected Event Actual Forecast Previous
0 0 02:00 GBP Low Volatility Expected U.K. Construction Output (YoY) (Jan) 9.9% 9.2% 7.4%
1 1 02:00 GBP Low Volatility Expected Construction Output (MoM) (Jan) 1.1% 0.5% 2.0%
2 2 02:00 GBP High Volatility Expected GDP (MoM) 0.8% 0.2% -0.2%
3 3 02:00 GBP High Volatility Expected GDP (YoY) 10.0% 9.3% 6.0%