Shubham R
Shubham R

Reputation: 7634

Converting pandas.core.series.Series to dataframe with appropriate column values python

i'm running a function in which a variable is of pandas.core.series.Series type.

type of the series shown below.

<class 'pandas.core.series.Series'>
product_id_y    1159730
count                 1
Name: 6159402, dtype: object

i want to convert this into a dataframe,such that, i get

product_id_y    count
1159730           1

i tried doing this:

series1 = series1.to_frame()

but getting wrong result

after converting to dataframe

              6159402
product_id_y  1159730
count               1

after doing reset index i'e series1 = series1.reset_index()

           index  6159402
 0  product_id_y  1159730
 1         count        1

is there anny other way to do this??

Upvotes: 20

Views: 119210

Answers (2)

PixelPioneer
PixelPioneer

Reputation: 4170

Sample:

import pandas as pd

df = pd.DataFrame({'Name': ['Will','John','John','John','Alex'],
                   'Payment':  [15, 10, 10, 10, 15],
                   'Duration':    [30, 15, 15, 15, 20]})

You can print by converting the series/dataframe to string:

> print (df.to_string())
   Duration  Name  Payment
0        30  Will       15
1        15  John       10
2        15  John       10
3        15  John       10
4        20  Alex       15

> print (df.iloc[1].to_string())
Duration      15
Name        John
Payment       10

Upvotes: 4

jezrael
jezrael

Reputation: 862396

You was very close, first to_frame and then transpose by T:

s = pd.Series([1159730, 1], index=['product_id_y','count'], name=6159402)
print (s)
product_id_y    1159730
count                 1
Name: 6159402, dtype: int64

df = s.to_frame().T
print (df)
         product_id_y  count
6159402       1159730      1

df = s.rename(None).to_frame().T
print (df)
   product_id_y  count
0       1159730      1

Another solution with DataFrame constructor:

df = pd.DataFrame([s])
print (df)
         product_id_y  count
6159402       1159730      1

df = pd.DataFrame([s.rename(None)])
print (df)
   product_id_y  count
0       1159730      1

Upvotes: 38

Related Questions