我想添加一个列,它是特定列中唯一值的索引。在
原始数据帧是:
Team Rank Year Points
0 Riders 1 2014 876
1 Riders 2 2015 789
2 Devils 2 2014 863
3 Devils 3 2015 673
4 Kings 3 2014 741
5 kings 4 2015 812
6 Kings 1 2016 756
7 Kings 1 2017 788
8 Riders 2 2016 694
9 Royals 4 2014 701
10 Royals 1 2015 804
11 Riders 2 2017 690
最理想的是:
^{pr2}$我定义了一个函数来帮助我:
def gen_countrycode(df):
grouped = df.groupby('Country Name')
Countries=df['Country Name'].unique()
group_num=range(len(df.groupby(['Country Name']).groups))
newdf=pd.DataFrame()
for i in group_num:
country=Countries[i]
country_group=grouped.get_group(country)
country_group['country code']=i
newdf=pd.concat([newdf,country_group], ignore_index=True)
return newdf
定义部分正常运行,但当我将其应用于数据帧时,出现错误:
line 2, in gen_countrycode
grouped = df.groupby('Country Name')
AttributeError: **'function' object has no attribute 'groupby'**
不知道为什么不能在函数中操作数据帧。 顺便说一句,如果有更好的方法来生成这样的“组码”,谢谢你的启发!在
使用^{} :
相关问题 更多 >
编程相关推荐