Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Groupby字符串的一部分_Python_Pandas - Fatal编程技术网

Python Groupby字符串的一部分

Python Groupby字符串的一部分,python,pandas,Python,Pandas,我正在按英国邮政编码对交易列表进行分组,但我只想按邮政编码的第一部分进行分组。因此,英国邮政编码分为两部分,向外和向内,由[空格]分隔。e、 g.W1 5DA subtotals = df.groupby('Postcode').count() 我现在的做法是,我现在考虑的做法是在数据框中添加另一列,只使用邮政编码列的第一个单词,然后根据该列进行分组。。。但我想知道有没有更简单的方法 谢谢我想您需要由第一空间创建的groupbybySeries: subtotals = df.groupby(

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

subtotals = df.groupby('Postcode').count()
我现在的做法是,我现在考虑的做法是在数据框中添加另一列,只使用邮政编码列的第一个单词,然后根据该列进行分组。。。但我想知道有没有更简单的方法


谢谢

我想您需要由第一空间创建的
groupby
by
Series

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

同时检查

您的邮政编码是否以空格分隔,例如
'W1 5DA
?如果是这样,您可以为第一部分添加一个新列
df['town_code']=df['Postcode'].str.split().str[0]
请提供。我讨厌读字里行间的东西,也不想弄明白你真正的意思。我想你需要
subtotals=df.groupby(df['Postcode'].str.split().str[0]).count()
Super,如果我的答案有用,别忘了。谢谢