Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DataFrame apply results in a DataFrame when lambda returns a list of length equal to the number of DataFrame features #16353

Closed
gsmafra opened this issue May 14, 2017 · 1 comment · Fixed by #18577
Labels
Apply Apply, Aggregate, Transform, Map Reshaping Concat, Merge/Join, Stack/Unstack, Explode
Milestone

Comments

@gsmafra
Copy link

gsmafra commented May 14, 2017

Hello guys, I'm using the apply method with axis=1 argument and returning a list for each row. The weird thing is when the length of this list is equal to the number of features in the original dataframe, this apply returns another dataframe, and a series if anything else. I don't know if this is intended, but it was very unexpected.

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randn(6, 3), columns=['A', 'B', 'C'])

ans1 = df.apply(lambda x: [1, 2, 3], axis=1)
ans2 = df.apply(lambda x: [1, 2], axis=1)

assert type(ans1) is pd.DataFrame
assert type(ans2) is pd.Series
@jreback
Copy link
Contributor

jreback commented May 15, 2017

see #15628 and linked issues.

.apply infers the output type based on the input shape. Returning an arbitrary shape breaks this guarantee and the results have to be coerced to the existing structure.

@jreback jreback closed this as completed May 15, 2017
@jreback jreback added the Reshaping Concat, Merge/Join, Stack/Unstack, Explode label May 15, 2017
@jreback jreback added this to the No action milestone May 15, 2017
@jreback jreback added the Apply Apply, Aggregate, Transform, Map label Sep 20, 2017
@jreback jreback modified the milestones: No action, 0.22.0 Nov 30, 2017
jorisvandenbossche pushed a commit that referenced this issue Feb 7, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Apply Apply, Aggregate, Transform, Map Reshaping Concat, Merge/Join, Stack/Unstack, Explode
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants