Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert pandas single column data frame to series or numpy vector [duplicate]

Tags:

python

pandas

I have the following data frame just single column.

import pandas as pd tdf =  pd.DataFrame({'s1' : [0,1,23.4,10,23]}) 

Currently it has the following shape.

In [54]: tdf.shape Out[54]: (5, 1) 

How can I convert it to a Series or a numpy vector so that the shape is simply (5,)

like image 376
neversaint Avatar asked Oct 28 '15 07:10

neversaint


People also ask

How do I turn a column into a series in pandas?

Convert Specific or Last Column of Pandas DataFrame to Series. To convert the last or specific column of the Pandas dataframe to series, use the integer-location-based index in the df. iloc[:,0] . For example, we want to convert the third or last column of the given data from Pandas dataframe to series.

How do I create a NumPy array from a DataFrame column?

Convert Select Columns into Numpy Array You can convert select columns of a dataframe into an numpy array using the to_numpy() method by passing the column subset of the dataframe. For example, df[['Age']] will return just the age column.

Can we convert DataFrame to NumPy array?

to_numpy() – Convert dataframe to Numpy array. Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of Dataframe. to_numpy() method.


1 Answers

You can simply index the series you want. Example -

tdf['s1'] 

Demo -

In [24]: tdf =  pd.DataFrame({'s1' : [0,1,23.4,10,23]})  In [25]: tdf['s1'] Out[25]: 0     0.0 1     1.0 2    23.4 3    10.0 4    23.0 Name: s1, dtype: float64  In [26]: tdf['s1'].shape Out[26]: (5,) 

If you want the values in the series as numpy array, you can use .values accessor , Example -

In [27]: tdf['s1'].values Out[27]: array([  0. ,   1. ,  23.4,  10. ,  23. ]) 
like image 166
Anand S Kumar Avatar answered Sep 23 '22 06:09

Anand S Kumar