Np. Ones_Like() Not Returning an Array
According to Numpy Manual, Ones_Like() Should Return an Array, Which Is Similar to Log(). However, When I Apply Them to Pandas Groupby, I Get Different...
According to numpy manual, ones_like() should return an array, which is similar to log(). However, when I apply them to pandas groupby, I get different formats. Do I write anything wrong?
y = pd.DataFrame({'id':[1,1,2,2,2], 'b':[2,3,1,1,2]})
print(y)
id b
0 1 2
1 1 3
2 2 1
3 2 1
4 2 2
log_y = y.groupby('id').apply(lambda x: np.log(x))
print(log_y)
id b
0 0.000000 0.693147
1 0.000000 1.098612
2 0.693147 0.000000
3 0.693147 0.000000
4 0.693147 0.693147
one_y = y.groupby('id').apply(lambda x: np.ones_like(x))
print(one_y)
id
1 [[1, 1], [1, 1]]
2 [[1, 1], [1, 1], [1, 1]]
dtype: object
1 Answer
I haven't studied the groupby docs, but with a bit of exploration I find apply iterates on the "groups", each of which is a dataframe.
In [795]: y.groupby('id').apply(lambda x: x.shape)
Out[795]:
id
1 (2, 2)
2 (3, 2)
ones_like takes the shape of the argument, and uses that to make a new array. Each of the arrays has the shape shown above.
In [794]: one_y.to_numpy()
Out[794]:
array([array([[1, 1],
[1, 1]]),
array([[1, 1],
[1, 1],
[1, 1]])], dtype=object)
The log_y case apparently reassembles those 2 frames back into one. I suppose that's documented.