简体   繁体   中英

Find size of numpy array within a Panda dataframe in python

I would like to get the size of each numpy array within a panda. How do I do this? I have:

          x          y                      z
0  [1, 2, 3, 4]  [8, 9, 7]              [8, 9, 7]
1  [2, 3, 4, 8]  [9, 8, 1]  [9, 8, 1, 6, 7, 8, 9]
2     [5, 6, 7]  [3, 4, 1]              [3, 4, 1]


cars= pd.DataFrame({'x': [[1,2,3,4],[2,3,4,8],[5,6,7]],
                    'y': [[8,9,7],[9,8,1],[3,4,1]],
                    'z': [[8,9,7],[9,8,1,6,7,8,9],[3,4,1]]})

I want:

   x  y  z
0  4  3  3
1  4  3  7
2  3  3  3

I know how to get the shape and size of the entire DataFrame, but not how to combine them with size of each block.

print(cars)
print(cars.size)
print(cars.shape)

Use Series.str.len in DataFrame.apply for precessing all columns:

df = cars.apply(lambda x: x.str.len())
print (df)
   x  y  z
0  4  3  3
1  4  3  7
2  3  3  3

If no missing values use DataFrame.applymap for element-wise apply function len :

df = cars.applymap(len)

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.

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