Python Forum
new help with dictionary and dataframe iteration - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: new help with dictionary and dataframe iteration (/thread-30287.html)



new help with dictionary and dataframe iteration - AlphFinan - Oct-13-2020

Hello folks

I am trying to iterate through a dataframe nested in a dictionary and assign period numbers in a new column to each row in the dataframe. The code below is what I have so far and what that does is assign the number of the dictionary key to all the rows in that dataframe.

Goal:

-Dictionary Key 01: Consisting of a DataFrame with 10 rows; create new column called 'Period' and assign Period + row number to each (Period 1, Period 2,..., Period 10)
-Dictionary Key 02: Consisting of a DataFrame with 11 rows; create new column called 'Period' and assign Period + row number to each (Period 1, Period 2,..., Period 11)
-...
-...
-...
-...
-Dictionary Key 07: Consisting of a DataFrame with 9 rows; create new column called 'Period' and assign Period + row number to each (Period 1, Period 2,..., Period 9)

>for i in range(0, len(data_year_list)):
>>for year in year_list_dict[data_year_list[i]].iterrows():
>>>year_list_dict[data_year_list[i]]['Period'] = 'Period ' + str(i)

This is spitting out:

-Dictionary Key 01: Consisting of a DataFrame with 10 rows; create new column called 'Period' and assign Period + row number to each (Period 1, Period 1,..., Period 1)
-Dictionary Key 02: Consisting of a DataFrame with 11 rows; create new column called 'Period' and assign Period + row number to each (Period 2, Period 2,..., Period 2)
-...
-...
-...
-...
-Dictionary Key 07: Consisting of a DataFrame with 9 rows; create new column called 'Period' and assign Period + row number to each (Period 7, Period 7,..., Period 7)


Thanks in advance for the help with this.