Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.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
子字符串或正则表达式上的Pandas grouppy_Pandas_Python 2.7_Dataframe_Pandas Groupby - Fatal编程技术网

子字符串或正则表达式上的Pandas grouppy

子字符串或正则表达式上的Pandas grouppy,pandas,python-2.7,dataframe,pandas-groupby,Pandas,Python 2.7,Dataframe,Pandas Groupby,给定一个数据帧。 如何在列“a”上执行groupby,以便将所有以相同字符串开头的行分组在一起。比较部分的末尾是。。(这里y_s1和y_s2组合在一起,而不是x_s1) 下面是一个简单的例子: raw_data = {'a': ['y_s2', 'y_s1', 'x_s1'], 'b': [1,2,3]} df = pd.DataFrame(raw_data, columns = ['a', 'b']) 大概是这样的: grp = df.groupby(df['a'].str[:2]) ##

给定一个数据帧。 如何在列“a”上执行groupby,以便将所有以相同字符串开头的行分组在一起。比较部分的末尾是
。(这里y_s1和y_s2组合在一起,而不是x_s1)

下面是一个简单的例子:

raw_data = {'a': ['y_s2', 'y_s1', 'x_s1'], 'b': [1,2,3]}
df = pd.DataFrame(raw_data, columns = ['a', 'b'])
大概是这样的:

grp = df.groupby(df['a'].str[:2])  ## groups on first 2-letters of column `a`
您可以在此groupby上执行
计数
,并检查以
x
开头的行是否分组在一起,以及以
y
开头的行是否分组在一起

In [1545]: df.groupby(df.a.str[:2]).count()                                                                                                                                                                 
Out[1545]: 
    a  b
a       
x_  1  1
y_  2  2
在OP的评论之后,有一种更普遍的方法:

## Split the string on `_` and create 2 separate columns

In [1572]: df['a1'], df['a2'] = df['a'].str.split('_', 1).str 
In [1573]: df                                                                                                                                                                                               
Out[1573]: 
      a  b a1  a2
0  y_s2  1  y  s2
1  y_s1  2  y  s1
2  x_s1  3  x  s1


## Groupby on `a1`(the part before `_`)

In [1577]: df.groupby('a1').count().drop('a2', 1)                                                                                                                                                           
Out[1577]: 
    a  b
a1      
x   1  1
y   2  2
没有复杂正则表达式的另一种方法;
您可以将
extract
regex
模式一起使用

df.groupby(df['a'].str.extract('(^[^_]*)')[0])['b'].sum()
输出:

0
x    3
y    3
Name: b, dtype: int64
0
x    3
y    3
Name: b, dtype: int64