Home > Mobile >  Two different beaviour for .tolist() IndexError
Two different beaviour for .tolist() IndexError

Time:12-21

I looping over on dataframe df1 to look for maximum order and then I want to take discount_first to assign to max order.

For one dataset everything goes OK

new_rate_1 = []
for value in df1["maximum_order"]:
    new_val = df[df["New_Order_Lines"]==value]["discount_first"]
    new_val = new_val.tolist()[0]
    new_rate_1.append(new_val)
new_rate_1 

[-1.3,
 -1.3,
 0.35,
 0.8,
 0.75,
 0.55,
 0.8,
 0.85,
 0.4,
 0.75,
 0.85,
 0.85,
 0.55,
 0.45,
 0.8,
 0.65,
 0.55,
 0.85,
 0.35,
 0.85,
 0.9,
 0.5,
 0.55,
 -0.6,
 0.85,
 0.75,
 0.35,
 0.15,
 0.55,
 0.7,
 0.8,
 0.85,
 0.75,
 0.65,
 0.75,
 0.75,
 0.35,
 0.85,
 0.4,
 ...
 ....
]

for other data set i start getting error ?

IndexError: list index out of range

If I dont index the list within the look I dont get error and output looks like this

 [[0.8],
 [0.8],
 [0.55],
 [0.55],
 [0.55],
 [0.85],
 [0.55],
 [0.85],
 [0.85],
 [0.65],
 [0.65],
 [0.75],
 [0.7]
 .....
  • any suggestion/advice how can I get rid of behaviour?

Thanks in advance

CodePudding user response:

How about using this

# new_val = new_val.tolist()[0]
new_val = new_val.values.flatten()[0]

CodePudding user response:

Why looping at all when you can do it without a loop?

you can use isin() tolist() method:

new_rate_1 =df.loc[df["New_Order_Lines"].isin(df1["maximum_order"]),"discount_first"].tolist()
  • Related