从5个数字的值中获取前2个数字,并在pandas的新列中输入

问题描述 投票:1回答:2

我一直在寻找解决这个问题的时间:我想对包含5个数字(整数)的列进行排序。然后我想使用此值的前2个数字进行分组。然后我想计算那些分组。

有一个简单的方法吗?我用它来计算:

print(worksheet['postalcolumn'].value_counts())

postalcolumn就像那个74660,745667,78320,71345我想要一个像74,74,78,71那样的新专栏

python-3.x pandas slice pandas-groupby
2个回答
1
投票

将列的dtype转换为字符串并使用strslicer,您可以使用:

worksheet['new_col']=worksheet['postalcolumn'].astype(str).str[:2].astype(int)

0
投票

假设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
© www.soinside.com 2019 - 2024. All rights reserved.