How to count the number of elements in a list and create a new column?

Related searches

I have a df as follows:

```   Col1                                           Col2
0                                     [7306914, 7306915]
1                                     [7295911, 7295912]
2                                              [7324496]
3                                     [7294109, 7294110]
4                                              [7313713]
```

The second column is a list. what I would like is to create a new column that contains the total number of elements in the list

Expected Output:

```   Col1        Col2           Col3
0    [7306914, 7306915]      2
1    [7295911, 7295912]      2
2    [7324496]               1
3    [7294109, 7294110]      2
4    [7313713]               1
```

Use `Series.str.len`. This is a vectorized method and is more efficient than `apply` function, which is essentially `looping` under-the-hood:

```df = pd.DataFrame([{'Col1': 0, 'Col2': [7306914, 7306915]}, {'Col1': 1, 'Col2': [7295911, 7295912]}, {'Col1': 2, 'Col2': [7324496]}, {'Col1': 3, 'Col2': [7294109, 7294110]}, {'Col1': 4, 'Col2': [7313713]}])

df['Col3'] = df['Col2'].str.len()
```

[out]

```print(df)

Col1                Col2  Col3
0     0  [7306914, 7306915]     2
1     1  [7295911, 7295912]     2
2     2           [7324496]     1
3     3  [7294109, 7294110]     2
4     4           [7313713]     1
```

Getting frequency counts of a columns in Pandas DataFrame , This method can be used to count frequencies of objects over single columns. After grouping a DataFrame object on one column, we can apply� Use Advanced Filter to create a list of the unique entries in the appropriate column. Use the =Countif function to count the number of times each unique entry appears in the original list. Sort,

Try this:

```df_tmp = pd.DataFrame({'col1':[[1,2,3], [1,2]]}).reset_index()
In [360]:

Out[360]:
index   col1
0   0       [1, 2, 3]
1   1       [1, 2]
In [364]:

df_tmp['len'] = df_tmp.apply(lambda x: len(x['col1']), axis=1)
In [365]:

df_tmp
Out[365]:
index   col1        len
0   0       [1, 2, 3]   3
1   1       [1, 2]      2
```

Apply should be most faster way for that.

Use pandas.DataFrame.count to count the number of elements , Apply a conditional to each element of a column by applying the conditional to the entire DataFrame column. Use the previous result to generate a subset of the � Build a new list of sizes of internal lists. Then pass the list to sum () to get total number of elements in list of lists i.e. # List of lists. listOfElems2D = [ [1,2,3,45,6,7], [22,33,44,55], [11,13,14,15] ] # Get the size of list of list using list comprehension & sum () function.

Using the `DataFrame.apply()` or `DataFrame.apply()` like this:

```df['Col3'] = df['Col2'].apply(len)
```