w3resource

Pandas Data Series: Convert the first column of a DataFrame as a Series

Pandas: Data Series Exercise-8 with Solution

Write a Pandas program to convert the first column of a DataFrame as a Series.

Sample Solution :

Python Code :

import pandas as pd

d = {'col1': [1, 2, 3, 4, 7, 11], 'col2': [4, 5, 6, 9, 5, 0], 'col3': [7, 5, 8, 12, 1, 11]}
df = pd.DataFrame(data=d)

print("Original DataFrame")
print(df)

# Using iloc
s1 = df.iloc[:, 0]

# Alternatively, you can directly reference the column by name
#s1 = df['col1']

print("\n1st column as a Series:")
print(s1)
print(type(s1)) 

Sample Output:

Original DataFrame
   col1  col2  col3
0     1     4     7
1     2     5     5
2     3     6     8
3     4     9    12
4     7     5     1
5    11     0    11

1st column as a Series:
0     1
1     2
2     3
3     4
4     7
5    11
Name: col1, dtype: int64
<class 'pandas.core.series.Series'>                  

Explanation:

Here is the breakdown of the above exercise:

  • Import Pandas Library:
    import pandas as pd
    This line imports the Pandas library and assigns it the alias "pd" for easier reference.
  • Create a DataFrame:
    d = {'col1': [1, 2, 3, 4, 7, 11], 'col2': [4, 5, 6, 9, 5, 0], 'col3': [7, 5, 8, 12, 1, 11]} df = pd.DataFrame(data=d)
    This code creates a DataFrame (df) using a dictionary (d). Each key-value pair in the dictionary represents a column in the DataFrame.
  • Print Original DataFrame:
    print("Original DataFrame") print(df)
    This prints the original DataFrame (df) to the console.
  • Extract the First Column as a Series:
    s1 = df.iloc[:, 0]
    or alternatively:
    # s1 = df['col1']
    This line extracts the first column from the DataFrame as a Series (s1). The iloc[:, 0] indexer is used to select all rows (:) from the first column (0). Alternatively, you can directly reference the column by name (df['col1']).
  • Print the Result:
    print("\n1st column as a Series:") print(s1)
    This prints the extracted Series (s1) to the console.
  • Print the Type of the Series:
    print(type(s1))
    This prints the type of the Series (s1). The result will show that s1 is a Pandas Series.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to convert a NumPy array to a Pandas series.
Next: Write a Pandas program to convert a given Series to an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/pandas/python-pandas-data-series-exercise-8.php