Home > Software design >  how to convert a class tuple to pandas dataframe
how to convert a class tuple to pandas dataframe

Time:09-29

I have multiple tuple rows , that needs to convert into pandas dataframe

sample_data=

(1, 'stackoverflow, tags, users,count')

(2, 'gmail, outlook,apps,users,count')

(3, 'digital, marketing,credentials')

(4, 'langugaes,python,c,java')

(5, 'slack,teams')

I tried data =pd.Dataframe(sample_data) but throwing error

output should be

column1=index , column2=research_topics

  index    research_topics

   1    'stackoverflow, tags, users ,count'

   2    'Gmail outlook, apps, users, count'

   3    'digital marketing, credentials'

   4    'languages, python,c,java'

   5     'slack, teams'

   

CodePudding user response:

Wrap your sample_data as a list of tuples:

import pandas as pd

sample_data=[(1, 'stackoverflow, tags, users,count'),

(2, 'gmail, outlook,apps,users,count'),

(3, 'digital, marketing,credentials'),

(4, 'langugaes,python,c,java'),

(5, 'slack,teams')]
df = pd.DataFrame(sample_data, columns=['index', 'research_topics'])

print(df)

CodePudding user response:

you are looking for from_records (documentation). It can convert a list of tuples into a dataframe.

pd.DataFrame.from_records(data, columns=['index ', 'research_topics'])

and if you want "index" to be index, use `.set_index('index')'

(assuming here data is a list of tuples)

  • Related