Pandas 计算字符串模式并附加到列多索引

Pandas counting string pattern and appending to column multi index

我有这个数据框,我想计算一个模式出现的次数,然后附加到一个新列。在这种情况下,我感兴趣的模式是“MV=??”即 MV=5455 等

d = [{'AX':['Rec(POS=4,,REF=FF,, MV=55), Rec(POS=2,, REF=GH,, MV=23)'], 'AVF1':[], 'HI':['Rec(POS=2,,REF=RTD,, MV=23), Rec(POS=234,, REF=FFRE,, MV=00)'],'AV1':[], 'version_1':[]},
      {'AX':[], 'AVF1':['Rec(POS=43,,REF=FeF,, MV=5455), Rec(POS=2,, REF=GH,, MV=23), Rec(POS=231,, REF=JK, MV=TR)'], 'HI':[],'AV1':[], 'version_2':[]},
      {'AX':['Rec(POS=2342,,REF=FhF,, MV=1)'], 'AVF1':['Rec(POS=11,,REF=FF11,, MV=551)'], 'HI':[],'AV1':[], 'version_3':[]}]



frame = pd.DataFrame(d)


f = frame.T

lst = []
f['temp'] = f.index
for i in f.iloc[-3:, -1]:
  lst.append(i)
f = f.drop(columns={'temp'})

f.columns = [lst, f.columns]
f

ALTS = pd.DataFrame(index=f.index, columns=pd.MultiIndex.from_product([f.columns.levels[0], ['ALT']]))

f = pd.concat([f,ALTS], axis=1).sort_index(level=0, axis=1)
f = f.drop(f.index[[-1,-2,-3]])

f

期望的输出 您可以看到第 0 列有两个 MV 计数,第 2 列有一个 MV 计数,依此类推。

           version_1          version_2      version_3
           ALT                ALT            ALT

AX         2                  NaN            1
AVF1       NaN                3              1
HI         2                  NaN            NaN
AV1        NaN                NaN            NaN

我正在处理的较大数据框有更多列,我的网络很糟糕,所以我无法上传整个数据框。

我正在考虑使用类似下面的东西,但我有多个索引列:

f['ALT'] = f.0.str.extract('MV=??').count()

试试 applystr.count:

output = f.apply(lambda x: x.str[0].str.count("MV=")).dropna(how="all", axis=1)
output = output.rename(columns={c[1]: "ALT" for c in output.columns},level=1)

     version_1 version_2 version_3
           ALT       ALT       ALT
AX         2.0       NaN       1.0
AVF1       NaN       3.0       1.0
HI         2.0       NaN       NaN
AV1        NaN       NaN       NaN