将列添加到由python中的for循环计算的数据框中

Posted

技术标签:

【中文标题】将列添加到由python中的for循环计算的数据框中【英文标题】:add columns to a data frame calculated by for loops in python 【发布时间】: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]

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

【问题讨论】:

【参考方案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 中的行数一样多时才有效。

我希望这会有所帮助!

【讨论】:

找到你想要的东西了吗?

以上是关于将列添加到由python中的for循环计算的数据框中的主要内容,如果未能解决你的问题,请参考以下文章

将列添加到数据框列表并进行增量添加/循环通过 df 进行简单添加

使用条件将列更改为单独的数据框

Spark scala将数据框列复制到新数据框

将列添加到数据框中,测试其他列中的分类变量

将超链接添加到由 pandas 数据框 to_excel 方法创建的 excel 表

使用 R 中的多参数用户定义函数将列添加到数据框中