我如何通过从其他列中减去第一列来创建一个新的数据框?

问题描述 投票:0回答:1
import pandas as pd
df = {'a': [1,1,1], 'b': [3,3,3,], 'c': [5,5,5,], 'd': [7,7,7], 'e': [9,9,9]}
df1 = pd.DataFrame(df, columns = ['a', 'b', 'c', 'd', 'e'])
dg = {'b': [2,2,2], 'c': [4,4,4], 'd': [6,6,6], 'e': [8,8,8]}
df2 = pd.DataFrame(dg, columns = ['b', 'c', 'd', 'e'])
df1
    a   b   c   d   e
0   1   3   5   7   9
1   1   3   5   7   9
2   1   3   5   7   9

df1是我的原始数据框。我想通过从每一列中减去第a列来创建另一个数据框(取第a列与所有其他列的差值)。

df2
    b   c   d   e
0   2   4   6   8
1   2   4   6   8
2   2   4   6   8

df2是结果。

我将感谢你的帮助。

python pandas dataframe calculated-columns difference
1个回答
2
投票
df = df1.loc[:,'b':].apply(lambda x: x-df1['a'])
print(df)

打印。

   b  c  d  e
0  2  4  6  8
1  2  4  6  8
2  2  4  6  8

1
投票
df1.iloc[:,1:].sub(df1.a,axis=0)

    b   c   d   e
0   2   4   6   8
1   2   4   6   8
2   2   4   6   8

0
投票

一种方法是

import pandas as pd

df = {'a': [1,1,1], 'b': [3,3,3,], 'c': [5,5,5,], 'd': [7,7,7], 'e': [9,9,9]}
df1 = pd.DataFrame(df, columns = ['a', 'b', 'c', 'd', 'e'])

df2 = pd.DataFrame()
for col in df1.columns[1:]:
    df2[col] = df1[col] - df1[df1.columns[0]]
© www.soinside.com 2019 - 2024. All rights reserved.