【问题标题】:Use the X from for-loop as part of variable name (Pythnon)使用 for 循环中的 X 作为变量名的一部分(Python)
【发布时间】:2020-05-02 20:05:47
【问题描述】:


我有一个对 Pythonist 来说可能很明显的问题,但我无法通过谷歌搜索。

很快:

我想使用来自for x in my_data_headerx 作为我的变量名的一部分。例如,不要硬编码my_data.selected_column,而是使用my_data.x 循环遍历所有列。

更长:

我想根据从电子表格导入的科学数据制作箱线图。在一列中是我修剪数据集的治疗名称。其他是我想从中绘制箱线图的测量值。我需要循环测量列并导出箱线图。所以 for 循环的 x 必须用于: *选择列(在每个处理中),为箱线图命名,为导出的 .png 文件命名,...

我可以单独执行步骤,但不能组成循环。
在必须参考列标题的复杂任务中循环遍历电子表格列的推荐方法是什么? (如果需要,我会填写信息。)
我正在尝试从 RStudio/Markdown/Knit 切换到 Python。

提前谢谢!


【问题讨论】:

  • 为此目的使用my_data[x]

标签: arrays for-loop variables spreadsheet


【解决方案1】:

这是 pd.DataFrame 问题:我之前使用的 date.read 方法导入为非 pandas 兼容。如果有人觉得它有用,我会在下面通过我的工作代码。如果 SO 社区认为它无关紧要,请一起删除。

`import numpy as np`
`import pandas as pd
`import seaborn as sns

`data = pd.read_excel('/media/Data/my_file.xlsx', 0)`
`h=data.columns #read headers line`
`d = pd.DataFrame(data) 
`print(type(d)) #check that is <class 'pandas.core.frame.DataFrame'>`
`for x in h:`
`    yy=d[x] #forreference to column`
`    bp = sns.boxplot(x='Column_with_treatments', y=yy, data=data)  #make graphs`
`    fig = bp.get_figure()  #put created graph in to obeject fig`
`    nn=yy.name+'_name_you_want.png' #crate file name string`
`    print(nn) # it print in log the column name of present graph`
`    fig.savefig(nn) #save graph image`
`    #plt.show() # it would show each image, but you need to close it to continue`
`    plt.clf() #clear the present graph from memory`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-21
    • 2022-01-10
    • 2019-09-27
    • 1970-01-01
    • 2019-11-06
    • 2019-11-19
    • 2018-05-14
    • 1970-01-01
    相关资源
    最近更新 更多