Count separators in CSV rows with Pandas

  • A+
Category:Languages

I have a csv file as follows:

name,age something tom,20 

And when I put it into a dataframe it looks like:

df = pd.read_csv('file', header=None)       0           1 1    name        age 2    something   NaN 3    tom         20 

How would I get the count of a comma in the raw row data. For example, the answer should look like:

# in pseudocode df['_count_separators'] = len(df.raw_value.count(','))       0           1      _count_separators 1    name        age   1 2    something   NaN   0 3    tom         20    1 

 


Doing this

df = pd.read_csv('file', header=None) df2 = pd.read_csv('file', header=None,sep='|') # using another sep for read your csv again   df2['0'].str.findall(',').str.len() # then one row into one cell , using str find  0    1 1    0 2    1 3    5 Name: 0, dtype: int64  df['_count_separators']=df2['0'].str.findall(',').str.len() 

Data

name,age something tom,20 something,,,,,somethingelse 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: