3

I want to use apply(applymap) and lambda functions to get the column name for every element in dfx (a dataframe). The lambda function is used for mapping another dataframe into dfx, and it will be rewritten afterwards.

dfx

             A     B    C
2011-01-10   123   12   123 
2011-01-10   12    32   312
2011-01-11   44    1    30.99   

pseudocode

output = dfx.apply(lambda r:r.column)

I don't know how to write this part "r:r.column"

intended output

             A    B    C
2011-01-10   A    B    C 
2011-01-10   A    B    C
2011-01-11   A    B    C  

Any help is more than welcome! Thanks a lot!!

1
  • When you say that the function will be rewritten afterwards, do you mean that you need access to the column's values as well, or do you just need the column names? Commented Oct 2, 2018 at 18:10

2 Answers 2

1

You can assign via pd.DataFrame.iloc:

df.iloc[:] = df.columns

print(df)

            A  B  C
2011-01-10  A  B  C
2011-01-10  A  B  C
2011-01-11  A  B  C
Sign up to request clarification or add additional context in comments.

Comments

0

When you apply a function that function takes as an argument a Series corresponding to a row. You can change this to a column by passing the kwarg axis=1 to apply. A Series does not have columns (axis 1) - only an index (axis 0). Instead you can use the original DataFrame:

dfx.apply(lambda s: dfx.columns, axis=1)

returns

            A  B  C
2011-01-10  A  B  C
2011-01-10  A  B  C
2011-01-11  A  B  C

Note: There are certainly better ways of doing this that don't "use apply and lambda functions" as desired.

1 Comment

this doesn't work as reported I get Index([ 'A', 'B', ..]) at every row

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.