Python Groupby 字符串的一部分

标签 python pandas

我正在按英国邮政编码对交易列表进行分组,但我只想按邮政编码的第一部分进行分组。因此,英国邮政编码分为两部分,向外和向内,用[空格]分隔。例如W1 5DA。

subtotals = df.groupby('Postcode').count()

这是我现在正在做的方式,我现在考虑的方式是在 DataFrame 中添加另一列,仅使用邮政编码列的第一个单词,然后按该分组...但我想知道是否有更简单的方法。

谢谢

最佳答案

我认为您需要 split 创建的 Seriesgroupby按第一个空格:

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/

相关文章:

python - 如何验证向 Windows Azure 发出的管理服务请求?

python - Django 的 syncdb 失败,MySQL errno : 150

Python - 生成十六进制值的所有组合

python - 将 pandas 分析中的特定值提取到表中

python - 如何按 NAN 值拆分 Pandas 时间序列

python - 在不同条件下向 pandas Dataframe 添加列

python - 2 列行之间的豪斯多夫距离

python - 在 pytest 中,如何中止 fixture 拆卸?

python - 使用 Python markdown Treeprocessor 包装 etree 元素

python - 为什么我的 pandas 数据框使用这么多内存?