简体   繁体   中英

Count occurrences in Pandas data frame

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.

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)

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM