Reputation: 793
I have a python script that initially loads a csv file:
data= []
with open('data.csv', 'r') as f:
for line in f.readlines()[1:]:
data.append(re.split(r',',line.rstrip()))
But now I am dynamically generating the contents of this csv within python in what results to be a pandas DataFrame
. My question is what is the most efficient way to get the data to the desired format (list of lists).
An obvious way would be to save the dataframe to a csv and then load it back as above, and another one to convert directly somehow. Is the approach below the way to go?
data = df.values.tolist()
Upvotes: 0
Views: 31
Reputation: 14699
As you suggested, if you have a pandas dataframe df
, you can use df.values.tolist()
to get a list of lists of the values.
Here's an example:
>>> import pandas as pd
>>> df = pd.DataFrame([[1,2],[3,4],[5,6]])
>>> df.values
array([[1, 2],
[3, 4],
[5, 6]])
>>> df.values.tolist()
[[1, 2], [3, 4], [5, 6]]
>>>
Upvotes: 1