代码为:
df['号'] = df['编号'].groupby(df['部门']).rank(axis=0, method='first') # 根据部门分组进行编号
报错信息如下:
Exception in Tkinter callback
Traceback (most recent call last):
File "tkinter\__init__.py", line 1883, in __call__
File "分类整理工具.py", line 50, in lab
df['号'] = df['编号'].groupby(df['部门']).rank(axis=0, method='first') # 根据部门分组进行编号
File "pandas\core\groupby\groupby.py", line 2455, in rank
File "pandas\core\groupby\groupby.py", line 996, in _cython_transform
pandas.core.base.DataError: No numeric types to aggregate
其中编号列不是纯数字,不知道有没有影响
求帮助
对编号列根据数据情况用字符串函数处理即可,样例:
import pandas as pd
l = {"部门":['A','B','C','A','B'], "编号":['A1','B1','C1','A2','B2'],"人数": [3, 2, 2,3,2]}
df = pd.DataFrame(l)
print(df)
df['号']=df['编号'].str.extract('.*(\d+)',expand=True).groupby(df["部门"]).rank(axis=0,method='first').astype(int)
print(df)
如有帮助,请点击采纳。
已解决
因编号列不是纯数字,导致无法进行分组排序编号,临时解决方案为:
增加一列“顺序号”并从小到大进行编号,并将代码中的编号替换为顺序号即可完成,代码如下:
df['顺序号'] = range(1, len(df) + 1)
df['号'] = df['顺序号'].groupby(df['部门']).rank(axis=0, method='first') # 根据部门分组进行编号
这个方法为另辟思路,最终实现,得到结果。
不过还是希望得到其他更好的方法实现,望大佬指教!