saundankarro
saundankarro

Reputation: 7

Is there a way to create a Pandas series via string iteration?

I want to create a Pandas series that has a string and add a number/counter that iterates up to a certain number.

For example

Students = pd.Series(f"Student_{i}" for i in i < len(5))

and the output would be a pandas series that contains the following values:

['Student_1', 'Student_2', 'Student_3', 'Student_4', 'Student_5']

Upvotes: -5

Views: 79

Answers (4)

iBeMeltin
iBeMeltin

Reputation: 1787

You were on the right track but your syntax is wrong. for i in i < len(5) does nothing because you are never defining i.

Instead, you need to use a loop like this:

Students = pd.Series(f"Student_{i}" for i in range(1,6))

Output:

0    Student_1
1    Student_2
2    Student_3
3    Student_4
4    Student_5
dtype: object

Upvotes: 2

tdelaney
tdelaney

Reputation: 77407

The problem is that f"Student_{i}" for i in i < len(5) isn't valid. i < len(5) doesn't iterate anything so it can't be used as the value generator in a for loop. Use range(5) instead. range generates the numbers for your generator.

>>> import pandas as pd
>>> Students = pd.Series(f"Student_{i}" for i in range(1,6))
>>> Students
0    Student_1
1    Student_2
2    Student_3
3    Student_4
4    Student_5
dtype: object

Upvotes: 0

Daweo
Daweo

Reputation: 36700

You might do it following way

import pandas as pd
s = "Student_" + pd.Series(range(1,6)).astype(str)
print(s)

output

0    Student_1
1    Student_2
2    Student_3
3    Student_4
4    Student_5
dtype: object

Explanation: I created series from range(1,6) (observe that range is inclusice-exclusive) convert it to strs and prefix with Student_

Upvotes: 1

maxis112
maxis112

Reputation: 169

use a list comprehension within the pandas series constructor, see my code below;

import pandas as pd

#create pandas series with a string and counter
students = pd.Series([f"Student_{i}" for i in range(1, 6)])

print(students)

Upvotes: 2

Related Questions