Akshay Kalghatgi
Akshay Kalghatgi

Reputation: 453

Convert python pandas series to a dataframe and split the column into two

This is my series named table

Host
cds170.yyz.llnw.net     1
cds172.yyz.llnw.net     3
cds180.yyz.llnw.net     1
cds182.yyz.llnw.net     1
cds183.yyz.llnw.net     3
fcds113.yyz.llnw.net    1
Name: Host, dtype: int64

This is the dataframe that I want

Host                  count
cds170.yyz.llnw.net     1
cds172.yyz.llnw.net     3
cds180.yyz.llnw.net     1
cds182.yyz.llnw.net     1
cds183.yyz.llnw.net     3
fcds113.yyz.llnw.net    1

I have tried

table = pd.DataFrame(table)
table = pd.DataFrame(table.Host.str.split().tolist(), columns = ['Host', 'count'])

But I get

ValueError: Shape of passed values is (1, 1), indices imply (2, 1)

Can someone please help me do this?

Upvotes: 1

Views: 83

Answers (1)

EdChum
EdChum

Reputation: 394469

The following should work:

In [5]:

pd.DataFrame({'Host':s.index, 'Count':s.values})
Out[5]:
   Count                  Host
0      1   cds170.yyz.llnw.net
1      3   cds172.yyz.llnw.net
2      1   cds180.yyz.llnw.net
3      1   cds182.yyz.llnw.net
4      3   cds183.yyz.llnw.net
5      1  fcds113.yyz.llnw.net

So you can construct a dict inline and pass this as the data to a DataFrame ctor

Upvotes: 2

Related Questions