我一直在寻找解决这个问题的时间:我想对包含5个数字(整数)的列进行排序。然后我想使用此值的前2个数字进行分组。然后我想计算那些分组。
有一个简单的方法吗?我用它来计算:
print(worksheet['postalcolumn'].value_counts())
postalcolumn就像那个74660,745667,78320,71345我想要一个像74,74,78,71那样的新专栏
将列的dtype转换为字符串并使用str
slicer,您可以使用:
worksheet['new_col']=worksheet['postalcolumn'].astype(str).str[:2].astype(int)
假设worksheet['postalcolumn']
是list
类型,你可以这样做:
worksheet['new_col'] = [] # create an empty new column
for id in worksheet['postalcolumn']:
first_two = int(str(id)[:2]) # take the first two digits
worksheet['new_col'].append(first_two) # add the two digits to the new column