OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

For Loop Errors Solved by Splitting Loop Function [duplicate]

  • Thread starter Thread starter andrew1990
  • Start date Start date
A

andrew1990

Guest
I want to iterate over dataframes which have the same number of columns. Each dataframe as an ID column which has different names.

I am dropping any na rows from each df in this column, then wishing to add a new column which indicates the ID type.

The below code produces an error against the last line of the loop:

Code:
national_id_dfs = [df1, df2]
column_names = ['df1_ID', 'df2_ID']

for (df, id_col) in zip(national_id_dfs, column_names):
    df = df.dropna(subset=[id_col], inplace=True)
    df['ID Type'] = id_col
TypeError: 'NoneType' object does not support item assignment

However, splitting the loops as below works as expected.

Code:
national_id_dfs = [df1, df2]
column_names = ['df1_ID', 'df2_ID']

for (df, id_col) in zip(national_id_dfs, column_names):
    df = df.dropna(subset=[id_col], inplace=True)

for (df, id_col) in zip(national_id_dfs, column_names):
    df['ID Type'] = id_col

What is the issue with the first for loop?
<p>I want to iterate over dataframes which have the same number of columns. Each dataframe as an ID column which has different names.</p>
<p>I am dropping any na rows from each df in this column, then wishing to add a new column which indicates the ID type.</p>
<p>The below code produces an error against the last line of the loop:</p>
<pre><code>national_id_dfs = [df1, df2]
column_names = ['df1_ID', 'df2_ID']

for (df, id_col) in zip(national_id_dfs, column_names):
df = df.dropna(subset=[id_col], inplace=True)
df['ID Type'] = id_col
</code></pre>
<blockquote>
<p>TypeError: 'NoneType' object does not support item assignment</p>
</blockquote>
<p>However, splitting the loops as below works as expected.</p>
<pre><code>national_id_dfs = [df1, df2]
column_names = ['df1_ID', 'df2_ID']

for (df, id_col) in zip(national_id_dfs, column_names):
df = df.dropna(subset=[id_col], inplace=True)

for (df, id_col) in zip(national_id_dfs, column_names):
df['ID Type'] = id_col
</code></pre>
<p>What is the issue with the first for loop?</p>
 
Top