为熊猫中的所有列生成列矩阵

时间:2019-09-28 07:59:26

标签: python pandas dataframe python-3.6

我有一个由6列组成的数据框。什么是最快的生成矩阵的方法,该矩阵执行以下操作:

步骤1)col1 * col1a,col2 * col2a,col3 * col3a,col4 * col4a

步骤2)col_new =(col1 * col1a)-col2 * col2a)/(col1a-col2a)

使用for循环是其中的一种选择-但是这可能是更快的方法。

import pandas as pd
df=pd.DataFrame()
df['col1']=[100,200,300,400,500]
df['col1a']=[6,71,8,90,10]
df['col2']=[600,700,800,1900,100]
df['col2a']=[6,17,8,9,10]
df['col3']=[100,220,300,440,500]
df['col3a']=[1,22,3,44,5]

df[1x2]=(df['col1']*df['col1a']-df['col2']*df['col2a'])/(df['col1a']-df['col2a'])

我需要具有1x3、1x4、1x5、2x3、2x4等的列组合...

2 个答案:

答案 0 :(得分:1)

这是我的处理方法:

def new_col(df, col1, col2):
    """
    Add a new column, modifying the dataframe inplace.

    col1: int
        column counter in the first column name
    col2: int
        column counter in the second column name
    """
    nr = (
        df.loc[:, f"col{col1}"] * df.loc[:, f"col{col1}a"]
        - df.loc[:, f"col{col2}"] * df.loc[:, f"col{col2}a"]
    )
    dr = df.loc[:, f"col{col1}a"] - df.loc[:, f"col{col2}a"]

    df.loc[:, f"col{col1}X{col2}"] = nr / dr

我将使用所需的列组合调用此函数。例如。

new_col(df, 1, 2)

输出:

enter image description here

该呼叫从循环发出。

答案 1 :(得分:1)

显然,我的第一个答案仅与原始问题匹配:这是更新后的问题的答案:

from itertools import combinations
from functools import partial

primary_columns = df.columns[~df.columns.str.endswith("a")]

combs = combinations(primary_columns, 2)

def column_comparison(first, second, df):
    return  (df[first]*df[first+"a"]-df[second]*df[second+"a"])/(df[first+"a"] - df[second+"a"])

dct = {'{first}X{second}'.format(first=comb[0].lstrip("col"), second=comb[1].lstrip("col")): 
       partial(column_comparison, comb[0], comb[1]) for comb in combs}

因此,我们创建了一个字典,其中包含所需列的名称和正确的函数。

现在我们可以利用assign

df.assign(**dct)

获得

   col1  col1a  col2  col2a  col3  col3a         1X2         1X3          2X3
0   100      6   600      6   100      1        -inf  100.000000   700.000000
1   200     71   700     17   220     22   42.592593  191.020408 -1412.000000
2   300      8   800      8   300      3        -inf  300.000000  1100.000000
3   400     90  1900      9   440     44  233.333333  361.739130    64.571429
4   500     10   100     10   500      5         inf  500.000000  -300.000000 

在以前的版本中,我在这里使用lambda,但这不起作用-检查here以获得解释。我只有在使用partial找到解决方案后才意识到这一点。