Reputation: 165
I have the following data frame:
I'm looking to come up with this data frame:
which is counting the occurrences of pipe delimited strings in position and type column.
Upvotes: 0
Views: 632
Reputation: 4199
you could split each value and then apply count method. see example below
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')))
results in
Upvotes: 1
Reputation: 2361
The trick is to use 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
Though, you might also want to rename and concat them (assuming your DataFrame
is called 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)
Upvotes: 1