使用循环在数据框中重命名列

发布于 2025-02-09 09:25:58 字数 378 浏览 3 评论 0原文

说我有一个数据框(DF),如下所示 “在此处输入图像说明”

它的列3列都命名为Same(L,L,L,L)。我想根据其列位置将列命名为L1,L2和L3。我希望选择的外观如下所示。

“在此处输入图像说明”

我可以使用代码做到这一点 df.columns = ['input','l1','l2','l3']

但是,我相信必须在所有列(或选择的列)上循环(或选择的列),以便为任何DataFrame自动化这一点。

非常感谢您的回复。

Say I have a dataframe (df) which looks as given below
enter image description here

It has columns 3 columns all named the same (L, L, L). I want to rename the columns as L1, L2 and L3 based on their column position. I expect the optput to look as given below.

enter image description here

I can do it using the code
df.columns = ['Input', 'L1', 'L2', 'L3']

However, I believe a way must be available where I loop over all columns (or chosen columns) so that this can be automated for any dataframe.

Many thanks in advance for the responses.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画尸师 2025-02-16 09:25:58

您使用

df.columns = [f'{col}{i}' if col == 'L' else col for i, col in enumerate(df.columns)]

You use

df.columns = [f'{col}{i}' if col == 'L' else col for i, col in enumerate(df.columns)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文