0

I am trying to count the delimiter from my CSV file using this piece of code:

import pandas as pd

df = pd.read_csv(path,sep=',')
df['comma_count'] = df.string_column.str.count(',')
print (df)

But I keep getting this error: 'DataFrame' object has no attribute 'string_column'. Trying to iterate through my dataframe had no avail.

I am trying to achieve this:

     id    val      new  comma_count
     id    val      new          2
0     a    2.0    234.0          2
1     a    5.0    432.0          2
2     a    4.0    234.0          2
3     a    2.0  23423.0          2
4     a    9.0    324.0          2
5     a    7.0      NaN          1
6   NaN  234.0      NaN          1
7     a    6.0      NaN          1
8     4    NaN      NaN          0

My file:

id,val,new
a,2,234
a,5,432
a,4,234
a,2,23423
a,9,324
a,7
,234
a,6,
4
3
  • Waht is print (df.columns) ? Error means there is no column string_column Commented Jun 17, 2021 at 11:55
  • Index(['id', 'val', 'new'], dtype='object') I am trying to count the delimiter over all columns (id, val and new) Commented Jun 17, 2021 at 11:58
  • well, you have 3 delimiters per row that are used to create your column with the sep=',' Commented Jun 17, 2021 at 11:59

1 Answer 1

1

Use different separator with select first column and count:

df1 = pd.read_csv(path,sep='|')
df['dot_count'] = df1.iloc[:, 0].str.count(',')
Sign up to request clarification or add additional context in comments.

7 Comments

My output is not showing the count (It`s just 0 for all lines). Also, I want to count the delimiters in my header too.
@Oliveira - Can you add small data sample with exepected ouput to question?
@Oliveira - so need count dot ? Not comma? also why in first row are 2?
added a sample of my file. its comma. sorry
comma count still 0 though
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.