df.values.to_list()
or list(df.values)
converts dataframe to list of lists, but the integer values are converted to float values
DataFrame is,
HSCode value year
0 2 0.18 2018
1 3 0.00 2018
2 4 12.48 2018
3 6 0.00 2018
4 7 1.89 2018
output required is
[[2,0.18,2018],[3,0.00,2018]..]
But df.values.tolist()
gives
[[2.0,0.18,2018.0],...]
At times, you may need to convert your pandas dataframe to List. To accomplish this task, ' tolist() ' function can be used.
Pandas series can be converted to a list using tolist() or type casting method. There can be situations when you want to perform operations on a list instead of a pandas object. In such cases, you can store the DataFrame columns in a list and perform the required operations.
Series is a one-dimensional labeled array capable of holding data of the type integer, string, float, python objects, etc.
You can get unique values in column (multiple columns) from pandas DataFrame using unique() or Series. unique() functions. unique() from Series is used to get unique values from a single column and the other one is used to get from multiple columns.
itertuples
list(map(list, df.itertuples(index=False)))
[[2, 0.18, 2018],
[3, 0.0, 2018],
[4, 12.48, 2018],
[6, 0.0, 2018],
[7, 1.89, 2018]]
And far less readable
[*map(list, zip(*map(df.get, df)))]
[[2, 0.18, 2018],
[3, 0.0, 2018],
[4, 12.48, 2018],
[6, 0.0, 2018],
[7, 1.89, 2018]]
You can use the intermediate numpy
records array to conserve datatypes, and then if you must, convert to a list.
This approach, while being quite fast, will leave you with a list of tuples, as opposed to a list of lists.
df.to_records(index=False).tolist()
[(2, 0.18, 2018),
(3, 0.0, 2018),
(4, 12.48, 2018),
(6, 0.0, 2018),
(7, 1.89, 2018)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With