简体   繁体   中英

Pandas returns nan when queried

This is my code while working with which I encountered this problem:

def getBill(basket):
    if len(basket) != 0:
        for index in range(len(df)):
            if df.iloc[index]["amount"] != df.iloc[index]["amountPayable"]:
                name = "     Promotion " + df.iloc[index]["promotion"] #The spacing is done for formatting   purposes 
                row = pd.DataFrame({"name": name, "price": price, "unit": unit, "amount": amount}, index=[index + 0.5]) #I have declared all the variables correctly
                df = df.append(row, ignore_index=False)
                df = df.sort_index().reset_index(drop=True) #This is what breaks the code

Returns:

name = "     Promotion " + df.iloc[index]["promotion"]
TypeError: can only concatenate str (not "float") to str

This occurs due to df.iloc[index]["promotion"] being nan at index = 2 , however when printed the dataframe basket returns these values:

  promotion  price  amount  amountPayable
0      None   2.00    0.55           0.55
1  get4pay3   0.50    5.00           4.00
2  get4pay3   1.25    2.00           0.00
3  get4pay3  10.00   10.00           9.00
4  get2pay1   1.75    9.00           5.00

The problem should occur due to resetting indexes (I am trying to insert into the middle using this method: Is it possible to insert a row at an arbitrary position in a dataframe using pandas? ). What could be causing this problem?

Convert to string before concatenating:

name = "     Promotion " + str(df.iloc[index]["promotion"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM