简体   繁体   English

如何计算 Python->Pandas->DataFrame 中每个索引的值的数量

[英]How to count the number of values for each index in Python->Pandas->DataFrame

I have the next DataFrame:我有下一个 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.我需要在 DataFrame 中创建新列 -> len_x1 并将每个单元格中的值的数量插入其中。

I need the next result:我需要下一个结果:

在此处输入图像描述

I will be grateful for help.我将不胜感激。

If possible count separator and add 1 use:如果可能,计数分隔符并添加1使用:

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+')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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