[英]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).我想使用apply(applymap) 和 lambda函数来获取dfx (数据框)中每个元素的列名。 The lambda function is used for mapping another dataframe into dfx , and it will be rewritten afterwards. lambda函数用于将另一个数据帧映射到dfx 中,之后将对其进行重写。
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"我不知道如何写这部分“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
:您可以通过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.当您apply
一个函数时,该函数将一个对应于一行的Series
作为参数。 You can change this to a column by passing the kwarg axis=1
to apply
.你可以通过传递kwarg更改为一列axis=1
至apply
。 A Series
does not have columns (axis 1) - only an index (axis 0). Series
没有列(轴 1) - 只有索引(轴 0)。 Instead you can use the original DataFrame:相反,您可以使用原始 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.注意:当然有更好的方法可以不按需要“使用 apply 和 lambda 函数”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.