1

I have the next DataFrame:

a = [{'x1':'a, b, c, d, e, f'}, {'x1':'a, b, c'}, {'x1':'a'}]
df = pd.DataFrame(a)
print(df)

I need to create the new column -> len_x1 in DataFrame and insert into it the amount of values in each cell.

I need the next result:

enter image description here

I will be grateful for help.

1 Answer 1

3

If possible count separator and add 1 use:

df['x1_len'] = df['x1'].str.count(',') + 1
print (df)
                 x1  x1_len
0  a, b, c, d, e, f       6
1           a, b, c       3
2                 a       1

Or count words:

df['x1_len'] = df['x1'].str.count('\w+')
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for help, in my situation I need str.count(',') + 1, because sometimes I have the next values -> 'a.r, a, b, b.r' ect.

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.