【问题标题】:How to write function to extract n+1 column in pandas如何编写函数以在熊猫中提取 n+1 列
【发布时间】:2019-12-02 19:05:58
【问题描述】:

我有一个包含 200 列的 excel 文件。第一列为否。访问次数,其他列是该访问次数的人数数据

Visits A B C D 2 10 0 30 40 3 5 6 0 1 4 2 3 1 0

我想编写一个函数,以便我有多个带有访问列和 A 的数据框;访问列和B,等等(我想写一个函数,因为将来列的数量会增加,我想自动化这个过程)。另外,我想用0去掉数据。

期望的输出:

数据框 1:

visits A

数据框 2:

Visits B 3 6 4 3

这是我的第一个问题。很抱歉,如果它没有正确构图。感谢您的帮助。

【问题讨论】:

  • 请使用代码语法编辑器发布表格和数据框,而不是图片。

标签: python-3.x pandas multiple-columns


【解决方案1】:

使用DataFrame.items:

for i,col in df.set_index('visits').items():
    print(col[col.ne(0)].to_frame(i).reset_index())

您可以创建一个字典以按列名称保存

dfs={i:col[col.ne(0)].to_frame(i).reset_index() for i,col in df.set_index('visits').items()}

【讨论】:

    猜你喜欢
    • 2018-02-28
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 2015-09-10
    • 2016-10-20
    • 2017-07-09
    • 1970-01-01
    相关资源
    最近更新 更多