Python set to array and dataframe

Viewed 20662

Interpretation by a friendly editor:

I have data in the form of a set.

import numpy as n , pandas as p
s={12,34,78,100}
print(n.array(s))
print(p.DataFrame(s))

The above code converts the set without a problem into a numpy array. But when I try to create a DataFrame from it I get the following error:

ValueError: DataFrame constructor not properly called!

So is there any way to convert a python set/nested set into a numpy array/dictionary so I can create a DataFrame from it?


Original Question:

I have a data in form of set . Code

 import numpy as n , pandas as p
 s={12,34,78,100}
 print(n.array(s))
 print(p.DataFrame(s))

The above code returns same set for numpyarray and DataFrame constructor not called at o/p . So is there any way to convert python set , nested set into numpy array and dictionary ??

4 Answers

Pandas can't deal with sets (dicts are ok you can use p.DataFrame.from_dict(s) for those)

What you need to do is to convert your set into a list and then convert to DataFrame:

import pandas as pd

s = {12,34,78,100}
s = list(s)
print(pd.DataFrame(s))

You can use list(s):

import pandas as p
s = {12,34,78,100}
df = p.DataFrame(list(s))
print(df)
import numpy as n , pandas as p

s={12,34,78,100}

#Create DataFrame directly from set 
df = p.DataFrame(s)

#Can also create a keys, values pair (dictionary) and then create Data Frame, 
#it useful as key will be used as Column Header and values as data
df1 = p.DataFrame({'Values': data} for data in s)
Related