在python中为for循环计算的数据帧添加列

2024-06-01 08:53:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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]

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


Tags: inimportrecreatingloopdfnewfor
2条回答

通常,您使用其内置的__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

据我所知,i,j,bina不是df的一部分。为其中的每一个构建数组,每个数组元素表示一个“row”,并且一旦为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中的行数相同时,此操作才有效。

我希望这有帮助!

相关问题 更多 >