我正在按英国邮政编码对交易列表进行分组,但我只想按邮政编码的第一部分进行分组。因此,英国邮政编码分为两部分,向外和向内,用[空格]分隔。例如W1 5DA。
subtotals = df.groupby('Postcode').count()
这是我现在正在做的方式,我现在考虑的方式是在 DataFrame 中添加另一列,仅使用邮政编码列的第一个单词,然后按该分组...但我想知道是否有更简单的方法。
谢谢
最佳答案
我认为您需要 split
创建的 Series
的 groupby
按第一个空格:
subtotals = df.groupby(df['Postcode'].str.split().str[0]).count()
示例:
df = pd.DataFrame({'Postcode' :['W1 5DA','W1 5DA','W2 5DA']})
print (df)
Postcode
0 W1 5DA
1 W1 5DA
2 W2 5DA
print (df['Postcode'].str.split().str[0])
0 W1
1 W1
2 W2
Name: Postcode, dtype: object
subtotals = df.groupby(df['Postcode'].str.split().str[0]).count()
print (subtotals)
Postcode
Postcode
W1 2
W2 1
另请检查What is the difference between size and count in pandas?
关于Python Groupby 字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41979933/