I have a dataframe as follows:
version count region listing
2 v2 2 CAN [7, 8]
2 v3 3 CAN [7, 8, 9]
I want to extract listing
list for each row and get the length. So I did the following:
group_v2_list = group[group['version'] == 'v2']['listing'].values
and I get output as [list([7, 8])]
. Here the type of listing
column is numpy.ndarray
which I get after using type(group_v2_list)
.
Now I want to get the number of elements in this group_v2_list
but I am unable to get it.
I tried len(group_v2_list)
and group_v2_list.size
but both are giving me 1
. I want to get the number of elements which should be 2
as 7, 8
.
How can I get that?
You do not need to access the numpy
representation for this.
One way is to use .loc
accessor to extract the series and find the length of the first element:
df = pd.DataFrame({'version': ['v2', 'v3'],
'count': [2, 3],
'region': ['CAN', 'CAN'],
'listing': [[7, 8], [7, 8, 9]]})
df_v2_list = df.loc[df['version'] == 'v2', 'listing']
res_v2 = len(df_v2_list[0])
# 2
If there are multiple elements in your filtered data, you can retrieve a list of their lengths by using pd.Series.map(len)
:
df_v_all_list = df.loc[df['version'].str.startswith('v'), 'listing']
res_all = df_v_all_list.map(len).tolist()
# [2, 3]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.