Search code examples
python-3.xpandasattributeerror

Is AttributeError working as it should pandas df


Trying to add a number (type float) from one of two columns in a pd dataframe using the following code:

"""
creating dict of {symbol:[spot, aggregate]
"""

abn_dict = defaultdict(lambda: [0, 0])

for (col, row) in abn_df.iterrows():
    try:
        row.loc["Quantity Long"].isnull()
        abn_dict[row.loc["Symbol"]][1] += row.loc["Quantity Short"]
    except AttributeError:
        abn_dict[row.loc["Symbol"]][1] += row.loc["Quantity Long"]

If the quantity long column is NaN, it should add the quantity short to the second element in the abn_dict values.

This is however not working with the above code and wanted to ask why.


Solution

  • As it is, you have no condition in your code. Also, as per documentation, pandas.DataFrame.iterrows() returns (index, row), note (col, row).

    Try refactoring like this:

    for _, row in abn_df.iterrows():
        if row.loc["Quantity Long"]:
            abn_dict[row.loc["Symbol"]][1] += row.loc["Quantity Short"]
        else:
            abn_dict[row.loc["Symbol"]][1] += row.loc["Quantity Long"]