熊猫数据框中的新列,其值会逐步增加

时间:2020-10-04 16:29:18

标签: python pandas dataframe

我有一个熊猫数据框,看起来像这样:

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

如何添加新列position,其值会逐步增加。

示例:

enter image description here

1 个答案:

答案 0 :(得分:2)

尝试一下。

    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