簡體   English   中英

I want to count the elements of a python list that is within a dataframe, and for the output to be a column in the dataframe. 我怎么做?

[英]I want to count the elements of a python list that is within a dataframe, and for the output to be a column in the dataframe. How do I do that?

所以,我有一個看起來像這樣的數據框:

| column_1 | column 2        |
| 0.       | [`a`, 'b', 'c'] |
| 1        | ['z', 'y']      |
| 2        | ['a']           |

我想要的 output 是一列(具有相同的索引號),如下所示:

| column_1 | column 2        | column 3|
| 0.       | [`a`, 'b', 'c'] | 3       |
| 1        | ['z', 'y']      | 2       |
| 2        | ['a']           | 1       |

做就是了:

df['column_3'] =  df['column_2'].apply(len)
print(df)

Output

   column_1   column_2  column_3
0         0  [a, b, c]         3
1         1     [z, y]         2
2         2        [a]         1

或者更hacky,使用str訪問器:

df['column_3'] = df['column_2'].str.len()
print(df)

Output

   column_1   column_2  column_3
0         0  [a, b, c]         3
1         1     [z, y]         2
2         2        [a]         1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM