pandas 基于panda Dataframe 中的其他列名创建自定义列名

9vw9lbht  于 2023-01-15  发布在  其他
关注(0)|答案(2)|浏览(173)

我有一个 Dataframe 如下:

我希望使用差异或使用列之间的任何其它计算来创建列。但是,我希望命名列,以便它反映所完成的操作。例如,我正在查找“源1”和“目标1”之间的差异,如下所示:

如何创建突出显示的列的自定义命名,特别是当我必须创建多个这样的列时。

avwztpqn

avwztpqn1#

只需遍历它,就可以使用f字符串进行命名

for col_a in df.columns:
   for col_b in df.columns:
      if col_a != col_b:
         df[f'{col_a} - {col_b}'] = df[col_a] - df[col_b]

如果你使用itertools(在python中预装),你可以使它更容易阅读(如@MustafaAydın所建议的):

import itertools
for col_a, col_b in itertools.permutations(df, 2):
    df[f'{col_a} - {col_b}'] = df[col_a] - df[col_b]

如果要执行多个操作,只需添加一行

import itertools
for col_a, col_b in itertools.permutations(df, 2):
    df[f'{col_a} - {col_b}'] = df[col_a] - df[col_b]
    df[f'{col_a} + {col_b}'] = df[col_a] + df[col_b]

如果您只想使用列的子集,例如,只从源到目的地,您可以执行以下操作:

import itertools
origins = [col for col in df.columns if col.startswith('Origin')]
destinations = [col for col in df.columns if col.startswith('Dest')]
for col_a, col_b in itertools.product(origins, destinations):
    df[f'{col_a} - {col_b}'] = df[col_a] - df[col_b]
    df[f'{col_a} + {col_b}'] = df[col_a] + df[col_b]
idfiyjo8

idfiyjo82#

这很简单。
让我们定义一个包含两列ab的 Dataframe :

df = pd.DataFrame({"a":[1,2,3,4],"b":[4,3,2,1]})

输出:

a   b
0   1   4
1   2   3
2   3   2
3   4   1

现在,让我们创建上述两列之间的差异

df["a-b"] = df["a"] - df["b"]

瞧!现在你有了一个新的专栏。

a   b   a-b
0   1   4   -3
1   2   3   -1
2   3   2   1
3   4   1   3

对于多次迭代计算,我们可以采用基于循环的方法:

df = pd.DataFrame({"a":[1,2,3,4],"b":[4,3,2,1],"c":[8,7,6,5]})

df["a-b"] = df["a"] -df["b"]

#if you want to calculate for every column combination
for i in df.columns:
    for j in df.columns:
        if i != j and "-" not in j and "-" not in i:
            df[f"{i}-{j}"] = df[i] - df[j]

此方法在一个循环中计算所有列之间的所有差异。
输出:

a   b   c   a-b a-c b-a b-c c-a c-b
0   1   4   8   -3  -7  3   -4  7   4
1   2   3   7   -1  -5  1   -4  5   4
2   3   2   6   1   -3  -1  -4  3   4
3   4   1   5   3   -1  -3  -4  1   4

相关问题