create pandas series using for loop in python

To create a pandas series using a for loop in Python, you can follow these steps:

  1. Import the pandas library:

    main.py
    import pandas as pd
    
    20 chars
    2 lines
  2. Initialize an empty list to store the values for the series:

    main.py
    data = []
    
    10 chars
    2 lines
  3. Define the for loop to generate the values for the series. Here, we are generating values from 1 to 5 using the range() function:

    main.py
    for i in range(1, 6):
        data.append(i)
    
    41 chars
    3 lines
  4. Create the pandas series using the data list:

    main.py
    my_series = pd.Series(data)
    
    28 chars
    2 lines

The final code would look something like this:

main.py
import pandas as pd

data = []

for i in range(1, 6):
    data.append(i)

my_series = pd.Series(data)
102 chars
9 lines

This would create a pandas series with the values: [1, 2, 3, 4, 5].

gistlibby LogSnag