简体   繁体   中英

python dataframe: return column name in apply lambda

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!!

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

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.

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