PParker
PParker

Reputation: 1511

New column in pandas dataframe with values which increase stepwise

I have a pandas dataframe which looks like this:

df = pd.DataFrame({
     'job': ['football','football', 'football', 'basketball', 'basketball', 'basketball', 'hokey', 'hokey', 'hokey', 'football','football', 'football', 'basketball', 'basketball', 'basketball', 'hokey', 'hokey', 'hokey'],
     'team': [4.0,5.0,9.0,2.0,3.0,6.0,1.0,7.0,8.0, 4.0,5.0,9.0,2.0,3.0,6.0,1.0,7.0,8.0],
     'cluster': [0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1]
     })

enter image description here

How can I add a new column position which stepwise increases in value.

Example:

enter image description here

Upvotes: 2

Views: 120

Answers (1)

gilf0yle
gilf0yle

Reputation: 1102

Try this.

    df = pd.DataFrame({
 'job': ['football','football', 'football', 'basketball', 'basketball', 'basketball', 'hokey', 'hokey', 'hokey', 'football','football', 'football', 'basketball', 'basketball', 'basketball', 'hokey', 'hokey', 'hokey'],
 'team': [4.0,5.0,9.0,2.0,3.0,6.0,1.0,7.0,8.0, 4.0,5.0,9.0,2.0,3.0,6.0,1.0,7.0,8.0],
 'cluster': [0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1]
 })
    po=[(x//3)+1 for x in range(len(df)) ]

    df["position"]=po

Upvotes: 2

Related Questions