【问题标题】:How to loop over an array of variables with the same form of name? [closed]如何遍历具有相同名称形式的变量数组? [关闭]
【发布时间】:2020-01-06 11:14:43
【问题描述】:

我有一个包含变量列表的数据框,例如 id_01-id_10。

我想遍历所有变量以打印每个变量的计数图(使用 seaborn 作为 sns):

预期输出:

sns.countplot(id_01)

sns.countplot(id_02)

sns.countplot(id_03)

...

sns.countplot(id_10)

这种循环的语法是什么? 谢谢

【问题讨论】:

  • id_01id_02 等单独的变量吗?还是数据框中的列等?
  • 'id_01' 是第一列的名称,'id_02' 是第二列的名称,以此类推

标签: python pandas loops


【解决方案1】:

如果您想处理数据框中的所有列:

for col in df.columns:
    sns.countplot(df[col])

。否则,请遵循您问题中的模式:

for i in range(1,11):
    column='id_'+"{0}".format(i).zfill(2)
    sns.countplot(df[column])

这将遍历数字 1-10 并将列设置为正确的列名。 zfill 将确保对于单个数字,column 等于 id_01 而不是 id_1。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多