【问题标题】:How to iterate for each column name and append it to a table or data frame in python如何迭代每个列名并将其附加到python中的表或数据框中
【发布时间】:2020-05-26 18:17:33
【问题描述】:

我想制作一个自定义的关联表,经过很长的脚本后,这是我的最终数据:

ID        a      ...  z                                           
1         76.0   ...  1.033004
2         257.0  ...  0.629641
3         99.0   ...  0.672139
4         52.0   ...  1.007708
5         129.0  ...  1.080922

这是我为我的自定义关联表为一个 vs 所有变量制作的脚本

pg.pairwise_corr(df_pvt, columns=[['a'], list(df_pvt.columns)], method='pearson')[['X','Y','r']].append
pg.pairwise_corr(df_pvt, columns=[['b'], list(df_pvt.columns)], method='pearson')[['X','Y','r']].append ......... #until variable z

如何在不输入变量名 'a' until 'z' 的情况下循环或选择特定的列号?

我是 python 新手。提前谢谢你

【问题讨论】:

    标签: python loops dataframe foreach data-science


    【解决方案1】:
    import pandas as pd
    
    data = pd.DataFrame({"ID": [1,2,3,4,5], "a": [76.0, 257.0, 99.0,52.0,129.0], "z": [1.033004, 0.629641, 0.672139,1.007708, 1.080922]}, columns=["ID", "a", "z"])
    
    true_columns = []
    
    for index, row in data.iterrows():
        true_col_list = [col for col in data.columns[1] if row[col]]
        true_columns.append(",".join(true_col_list))
    
    data["Columns"] = true_columns
    
    print(data)
    

    【讨论】:

    • 谢谢。如果我循环所有列的数量怎么办?像这样:true_columns = list(range(0,189)) for var in true_columns: corr = pg.pairwise_corr(df_pvt, columns=[[df_pvt.columns[var]], list(df_pvt.columns)], method='pearson')[['X','Y','r']].append
    【解决方案2】:

    由于我还不能发表评论,我认为这就是你要找的。如果我错了,请纠正我。

    for letter in 'abcdefghijklmnopqrstuvwxyz':
        pg.pairwise_corr(df_pvt, columns=[letter], list(df_pvt.columns)], method='pearson')[['X','Y','r']].append ....
    

    编辑:而且我认为,如果你想变得很酷和 pythonic(我在很多答案中都看到过),你不能自己写出字母表,而是用

    import string
    alphabet = string.ascii_lowercase # this equals 'abcdefghijklmnopqrstuvwxyz'
    
    # then iterate over the alphabet
    for letter in alphabet:
        # do your stuff here something something[letter] something :P
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      • 2014-11-25
      相关资源
      最近更新 更多