如果识别出某个元素,则在DataFrame中乘以值

问题描述 投票:3回答:2

我正在尝试创建一个程序,如果在其中识别出某个元素,它将乘以Dataframe行。例如,假设我有一个数据框:

A B C  D   E  F  G
1 0 -1 2  -4  C  5
4 1  5 7 -0.2 E  7

每当F列包含一个字母时,它应该使用以下数字乘以该行,但最后一列除外:C = 2.8 E = 1.4

所以最终输出将是这样的:

A   B   C    D     E    F  G
2.8 0  -2.8 5.6  -11.2  C  5
5.6 1.4  7  9.8  -0.28  E  7 

这是我正在尝试使用的代码:

import pandas as pd
import csv  

data= pd.read_csv("file.txt", sep= '\t')        
U= data.drop('xyz', axis= 1)

for col in U:
    U=col * 2.63

for Z in U:
    Z= pd.DataFrame(U)

with open('File.tbl', 'r') as  f:       
    P=list(f)
    del P[0]

B=[]
O=[]
for o in P:
    J=o.split()
    B.append(J[:4])
    T=(J[3:4])
    O.append(J[2:3])

column=['A','B','C','D']
Y= pd.DataFrame(B, columns= column)
D= Y.drop(0)
D=D.reset_index(drop=True)
M = pd.concat([Z, D], sort=False, axis= 1)    #Concatenating both the dataframes
S= pd.DataFrame(M)  

x=O
while True:
    x= C = 2.8
    x= E = 1.4

    col_Number = col + '_Number'
    Z[col_Number] = (Z[col]*(x) - Z.max()) / Z.max() - Z.min() #multiply the Z-score rows

在运行此程序时,它显示None,只显示最后一列ie。 E.上述公式选择每列的最大值和最小值并进行计算。 Z [col]是行值ie。要乘以的1,0,-1等。

我尝试过使用loc方法,但没有用。任何帮助将不胜感激。

python python-3.x dataframe formula matrix-multiplication
2个回答
1
投票

经过一番研究。

df.loc[df['F'] == 'C', ['A', 'B']] = df[['A', 'B']].apply(lambda x: x*2.8)

用通用术语df.loc[condition,[list of columns]] = df [[list of columns]].apply()

类似地,您可以在不同的语句中为不同的列使用不同的乘法因子。


0
投票

您可以创建列F的键的字典以及要乘以的相应值。迭代字典以选择所需的行,应用乘法并重新分配。

df = pd.DataFrame({'A': [1, 4],
                   'B': [0, 1],
                   'C': [-1, 5],
                   'D': [2, 7],
                   'E': [-4.0, -0.2],
                   'F': ['C', 'E'],
                   'G': [5, 7]})

mapping = dict(C=2.8, E=1.4)

for k in mapping:
    ix = df.eval(f'F=="{k}"')
    df.loc[ix, list('ABCDE')] = df.loc[ix, list('ABCDE')] * mapping.get(k)

df 
# returns:
     A    B    C    D      E  F  G
0  2.8  0.0 -2.8  5.6 -11.20  C  5
1  5.6  1.4  7.0  9.8  -0.28  E  7
© www.soinside.com 2019 - 2024. All rights reserved.