Python | Pandas Series.as_matrix ()

Series.as_matrix() Pandas Series.as_matrix() is used to transform a given series or frame object data into a Numpy array view.

Syntax: Series.as_matrix (columns = None)

Parameter:
columns: If None, return all columns, otherwise, returns specified columns.

Returns: values: ndarray

Example # 1: Use Series.as_matrix () to return an array representation - Series.as_matrix () of a given series object.

# import pandas as pd

import pandas as pd

 
# Create a series

sr = pd.Series ([ 'New York' , ' Chicago' , 'Toronto' , ' Lisbon' , 'Rio' ])

 
# Create index

index_ = [ 'City 1' , 'City 2' , ' City 3' , 'City 4' , ' City 5'

  
# set index

sr.index = index_

 
# Print series

print (sr)

Exit:

 City 1 New York City 2 Chicago City 3 Toronto City 4 Lisbon City 5 Rio dtype: object 

We will now use Series.as_matrix () to return an array representation for a given series object.

# return a massive view

result = sr.as_matrix ()

 
# Print result

print (result)

Output:

 ['New York' 'Chicago'' Toronto' 'Lisbon'' Rio'] 

As we can see in the output, Series.as_matrix () has successfully returned an array representation for this series object.

Example # 2: Use Series.as_matrix () to return an array representation - Series.as_matrix () of a given series object.

# import pandas as pd

import pandas as pd

 
# Create a series

sr = pd.Series ([  11 , 21 , 8 , 18 , 65 , 18 , 32 , 10 , 5 , 32 , None ])

 
# Create index
# apply annual rate

index_ = pd.date_range ( ' 2010-10-09 08:45' , periods   = 11 , freq = 'Y' )

  
# set index

sr.index = index_

 
# Print series

print (sr)

Output:

 2010-12-31 08:45 : 00 11.0 2011-12-31 08:45:00 21.0 2012-12-31 08:45:00 8.0 2013-12-31 08:45:00 18.0 2014-12-31 08:45:00 65.0 2015-12 -31 08:45:00 18.0 2016-12-31 08:45:00 32.0 2017-12-31 08:45:00 10.0 2018-12-31 08:45:00 5.0 2019-12-31 08:45: 00 32.0 2020-12-31 08:45:00 NaN Freq: A-DEC, dtype: float64 

Now we will use Se ries.as_matrix () to return an array representation for a given series object.

# return a massive view

result = sr.as_matrix ()

 
# Print result

print (result)

Output:

 [11. 21. 8. 18. 65. 18. 32. 10. 5. 32. nan] 

Like us we can see in the output, Series.as_matrix () has successfully returned an array representation for the given series object.





Get Solution for free from DataCamp guru