Resolving the TypeError Argument of Type 'float' Is Not Iterable Exception When Applying Lambda Functions to Non-Iterable Data Structures in Pandas

Understanding Python Lambda Functions and the TypeError Argument of Type ‘float’ is Not Iterable

Python lambda functions are small, anonymous functions that can be defined inline within a larger expression. They are often used in combination with higher-order functions like map(), filter(), and reduce().

In this article, we will delve into Python lambda functions, specifically the TypeError: argument of type 'float' is not iterable exception that may occur when attempting to apply a lambda function to a non-iterable data structure.

A Look at the apply() Function

The apply() function in pandas DataFrames applies a given function element-wise along sequence axis. When used with a lambda function, it can transform the elements of a series (a one-dimensional labeled array) or DataFrame column into another Series or DataFrame column.

Here’s an example:

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({
    'matrix': [
        {'status': 'ZERO_RESULTS'},
        {'distance': {'text': '3,899 km', 'value': 3898595}, 'duration': {'text': '1 day 13 hours', 'value': 133445}, 'status': 'OK'},
        {'distance': {'text': '2,065 km', 'value': 2065157}, 'duration': {'text': '20 hours 7 mins', 'value': 72393}, 'status': 'OK'}
    ]
})

# Apply a lambda function to the 'matrix' column
df['dist_value'] = df['matrix'].apply(lambda x: round((x['distance']['value']) / 1000) if "status" not in str(x) else None)

print(df)

The TypeError Exception

When attempting to apply a lambda function to the ‘matrix’ column, you may encounter the TypeError: argument of type 'float' is not iterable exception. This occurs when the x value in the lambda function is not an iterable (e.g., list or tuple) but rather a scalar value.

The Solution

To resolve this issue, we need to ensure that the x value is properly converted to a string before checking if it contains the key 'status'.

Here’s the corrected code:

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({
    'matrix': [
        {'status': 'ZERO_RESULTS'},
        {'distance': {'text': '3,899 km', 'value': 3898595}, 'duration': {'text': '1 day 13 hours', 'value': 133445}, 'status': 'OK'},
        {'distance': {'text': '2,065 km', 'value': 2065157}, 'duration': {'text': '20 hours 7 mins', 'value': 72393}, 'status': 'OK'}
    ]
})

# Apply a lambda function to the 'matrix' column
df['dist_value'] = df['matrix'].apply(lambda x: round((x.get('distance', {}).get('value', None)) / 1000) if isinstance(x, dict) else None)

print(df)

Additional Considerations

When working with nested dictionaries and lambda functions in pandas, it’s essential to consider the following:

  • Use str() to convert values to strings.
  • Utilize the .get() method to safely access dictionary keys. If a key is missing, this method returns a default value (None by default).
  • Employ isinstance(x, dict) checks to verify that x is a dictionary.

By addressing these considerations and properly applying lambda functions to non-iterable data structures, you can resolve the TypeError: argument of type 'float' is not iterable exception in Python.


Last modified on 2024-01-14