Python 使用一系列子字符串对数据帧进行分组

Python 使用一系列子字符串对数据帧进行分组,python,pandas,Python,Pandas,我有一个pandas数据框架,我想通过其中一列的子字符串对其进行分组。子字符串在另一个系列(或列表)中给出。我已经尝试了很多事情,但我就是无法让它发挥作用 我有这个: tst = pd.DataFrame({'id': [0, 11, 222, 3333, 44444], 'bla': ['ab', 'ba', 'ca', 'bc', 'db']}) test = pd.Series(['a', 'b', 'c', 'd']) 我想根据tst['bla'

我有一个pandas数据框架,我想通过其中一列的子字符串对其进行分组。子字符串在另一个系列(或列表)中给出。我已经尝试了很多事情,但我就是无法让它发挥作用

我有这个:

tst = pd.DataFrame({'id': [0, 11, 222, 3333, 44444],
                    'bla': ['ab', 'ba', 'ca', 'bc', 'db']})
test = pd.Series(['a', 'b', 'c', 'd'])
我想根据
tst['bla']
中是否包含“a”、“b”、“c”、“d”(来自
test
)对
tst
进行分组。df.apply()在这里是最好的

import pandas as pd
def funcx(x, test_str):
    return test_str in x['bla']


tst = pd.DataFrame({'id': [0, 11, 222, 3333, 44444],
                'bla': ['ab', 'ba', 'ca', 'bc', 'db']})
test = pd.Series(['a', 'b', 'c', 'd'])
result = {}
for xstring in test:
    result[xstring] = tst.apply(funcx, args=( xstring), axis=1)

print result
给我们

{'a': 0     True
1     True
2     True
3    False
4    False
dtype: bool, 'c': 0    False
1    False
2     True
3     True
4    False
dtype: bool, 'b': 0     True
1     True
2    False
3     True
4     True
dtype: bool, 'd': 0    False
1    False
2    False
3    False
4     True
dtype: bool}
然后可以使用它来选择相关行

>>print tst[result['a']]
  bla   id
  0  ab    0
  1  ba   11
  2  ca  222

比apply函数更优雅的是使用
result[xstring]=tst.bla.str.contains(xstring)
谢谢您的解决方案。首先,我有点担心我的真实数据(2000万个csv文件)需要很长时间才能使用for循环进行处理,但速度非常快。起初,我希望有一些一线熊猫魔术,但这是一个很好的简单的解决办法。谢谢