pandas

时间:2018-02-14 23:14:07

标签: python regex pandas dataframe

我有以下数据框a

  a=pd.DataFrame([[1,'bayern'],[2,'bayern_leverkusen'],[3,'Chelsea'],
                  [4,'manunited'],[5,'westhamunited'],[6,'mancity']]
                  ,columns=['no','club'])

我希望迭代列club,使club中的每个值都与club中的所有其他值进行迭代,并仅选择匹配为4的值或更多连续的角色。

对于eq bayernbayern_leverkusen应该进行过滤,因为它们包含相同的子字符串 bayern 。类似地,应该过滤manunitedwesthamunited,因为它们包含相同的子字符串 united

不应过滤

mancity,因为匹配的子字符串man仅为3。

预期产出:

     no    club
 0   1    bayern    
 1   2    bayern_leverkusen
 3   4    manunited
 4   5    westhamunited

1 个答案:

答案 0 :(得分:0)

import itertools
import pandas as pd
selector = pd.Series(False,index = a.index)
for first_index,second_index in itertools.combinations(a.index,2):
    club1 = a['club'][first_index]
    club2 = a['club'][second_index]
    for start in range(len(club1)-3):
        if club1[start:start+3] in club2:
            selector[first] = True
            selector[second] = True
            break
new_df = a.loc[selector]