答案 0 :(得分:1)
诀窍是使用collections.Counter
In [1]: from collections import Counter
In [2]: s = pd.Series(["AAA|BBB"])
In [3]: s.str.split("|").apply(Counter).apply(pd.Series)
Out[3]:
AAA BBB
0 1 1
但是,您可能还想重命名并连接它们(假设DataFrame
被称为df
):
# Counting
positions = df["POSITION"].str.split("|").apply(Counter).apply(pd.Series)
types = df["TYPE"].str.split("|").apply(Counter).apply(pd.Series)
# Tidying
positions = positions.fillna(0).add_suffix("_CNT")
types = types.fillna(0).add_suffix("_CNT")
# Joining
df = pd.concat([df, positions, types], axis=1)
答案 1 :(得分:1)
您可以拆分每个值,然后应用count方法。见下面的例子
df = pd.DataFrame.from_dict({'POSITION':['FRONT|FRONT|BACK|BACK|BACK'], 'TYPE': ['EXIT|EXIT|EXIT|WINDOW']})
df = df.assign(EXIT_CNTR = lambda x: x.TYPE.apply(lambda y: y.split('|').count('EXIT')))
df = df.assign(WINDOW_CNTR = lambda x: x.TYPE.apply(lambda y: y.split('|').count('WINDOW')))
df = df.assign(FRONT_CNTR = lambda x: x.POSITION.apply(lambda y: y.split('|').count('FRONT')))
df = df.assign(BACK_CNTR = lambda x: x.POSITION.apply(lambda y: y.split('|').count('BACK')))
结果