【问题标题】:add columns to a data frame calculated by for loops in python将列添加到由python中的for循环计算的数据框中
【发布时间】:2016-08-18 05:36:31
【问题描述】:
import re
#Creating several new colums with a for loop and adding them to the original df.
#Creating permutations for a second level of binary variables for df
for i in list_ib:
    for j in list_ib:
        if i == j:
            break
        else:            
            bina = df[i]*df[j]
            print(i,j)

i 是属于数据框 (df) 的二进制列,j 是相同的列。 我已经计算了每列与每列的乘法。我现在的问题是,如何将所有新的二进制乘积列添加到原始 df 中?

我试过了:

df = df + df[i,j,bina]

但我没有得到我需要的结果。有什么建议吗?

【问题讨论】:

    标签: python for-loop pandas


    【解决方案1】:

    通常您使用其内置的__setitem__() 将列添加到Dataframe,您可以使用[] 访问它。例如:

    import pandas as pd
    
    df = pd.DataFrame()
    
    df["one"] = 1, 1, 1
    df["two"] = 2, 2, 2
    df["three"] = 3, 3, 3
    
    print df
    
    # Output:
    #    one  two  three
    # 0    1    2      3
    # 1    1    2      3
    # 2    1    2      3
    
    list_ib = df.columns.values
    
    for i in list_ib:
        for j in list_ib:
            if i == j:
                break
            else:
                bina = df[i] * df[j]
                df['bina_' + str(i) + '_' + str(j)] = bina # Add new column which is the result of multiplying columns i and j together
    
    print df
    
    # Output:
    #        one  two  three  bina_two_one  bina_three_one  bina_three_two
    # 0    1    2      3             2               3               6
    # 1    1    2      3             2               3               6
    # 2    1    2      3             2               3               6
    

    【讨论】:

      【解决方案2】:

      据我了解,i,j,bina 不属于您的 df。为其中的每一个构建数组,每个数组元素代表一个“行”,一旦你准备好i,j,bina 的所有行,你就可以像这样连接:

      >>> new_df = pd.DataFrame(data={'i':i, 'j':j, 'bina':bina}, columns=['i','j','bina'])
      >>> pd.concat([df, new_df], axis=1)
      

      或者,一旦您收集了'i', 'j' and 'bina' 的所有数据并假设您将每个数据的数据放在一个单独的数组中,您可以这样做:

      >>> df['i'] = i
      >>> df['j'] = j
      >>> df['bina'] = bina
      

      这只有在这三个数组的元素数与 DataFrame df 中的行数一样多时才有效。

      我希望这会有所帮助!

      【讨论】:

      • 找到你想要的东西了吗?
      猜你喜欢
      • 2019-03-02
      • 1970-01-01
      • 2011-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-11
      • 2019-03-15
      相关资源
      最近更新 更多