Home > Blockchain >  How return list of tuples in python when using dataframes?
How return list of tuples in python when using dataframes?

Time:10-14

I need to return values in the format:

[("CarB", 2000), ("CarA", 2002)]

This is how I'm generating my list of tuples:

car_tuple = list(tuple(CAR_DF[['name_car','year']].to_records(index=False)))

But the values in car_tuple are not converted as tuples.

CodePudding user response:

As @psidom stated. You can get single quotes as follows

CAR_DF = pd.DataFrame({'name_car':['CarA','CarB'], 'year':[2000,2002]})



   name_car  year
0     CarA  2000
1     CarB  2002


s = [x for x in CAR_DF.agg(tuple,1)]

print(s)

[('CarA', 2000), ('CarB', 2002)]

CodePudding user response:

The problem was that list(CAR_DF[['name_car','year']].to_records(index=False)) don't return a list of tuples.

print(type(car_tuple[0])) returns <class 'numpy.record'>

and

print(type(car_tuple[0])) returns <class 'numpy.int32'>

In order to fix that, I've used:

CAR_DF_2 = CAR_DF[["name_car","year"]]
tup = [tuple(a) for a in CAR_DF_2.to_numpy()]
car_list_tuple = list(tup)
  • Related