Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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??

like image 451
Shubham R Avatar asked Dec 09 '16 06:12

Shubham R


People also ask

How do you convert a series to a DataFrame in Python with column names?

You can convert pandas series to DataFrame by using the pandas Series. to_frame() method. This function is used to convert the given series object to a DataFrame.

How do you convert a series to a DataFrame in Python?

to_frame() function is used to convert the given series object to a dataframe. Parameter : name : The passed name should substitute for the series name (if it has one).

Which of the following is used to convert a series to DataFrame?

The to_frame() function is used to convert Series to DataFrame. The passed name should substitute for the series name (if it has one).


1 Answers

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
like image 174
jezrael Avatar answered Sep 20 '22 04:09

jezrael