我有一个大数据框df_trial
,行命名为reaction
。其中有五个值,它们可能是:152Gd-p
,154Gd-p
,155Gd-p
,156Gd-p
,15Gd-p
,158Gd-p
,{{1 }}。下面的列包含与该步骤无关的信息,但是我希望根据“反应”中存在的字符串将下面的列乘以一个常数。我尝试将其应用为:
160Gd-p
但是,这不会乘以行中的值。
以下是我的数据框外观的示例:
for index, row in df_trial.iterrows():
if row['reaction'] == '152Gd-p':
row[2:]*=0.002
if row['reaction'] == '154Gd-p':
row[2:]*=0.0218
if row['reaction'] == '155Gd-p':
row[2:]*=0.148
if row['reaction'] == '156Gd-p':
row[2:]*=0.2047
if row['reaction'] == '157Gd-p':
row[2:]*=0.1565
if row['reaction'] == '158Gd-p':
row[2:]*=0.2484
if row['reaction'] == '160Gd-p':
row[2:]*=0.2186
很明显,在整个数据框中,它包含具有所有反应的行。
答案 0 :(得分:0)
您可以定义一个函数,将每行相乘,然后使用apply
将其应用于每行。
此外,为了改善条件,可以设置elif
而不是if
。这样可以避免每次都测试所有条件。
在答案中,我使用字典来保存系数。然后,我用reaction
键叫它。
代码在这里:
# Coefficients
multi_coef = {
'152Gd-p': 0.002,
'154Gd-p': 0.0218,
'155Gd-p': 0.148,
'156Gd-p': 0.2047,
'157Gd-p': 0.1565,
'158Gd-p': 0.2484,
'160Gd-p': 0.2186,
}
# Get columns name
columns = df.columns
# Function to apply to each row
def multiply_coef(row):
# If the reaction name is in the dictionary
if row.reaction in multi_coef.keys():
# Multiply by the reaction coefficient
row[columns[2:]] = row[columns[2:]] * multi_coef[row.reaction]
return row
# Apply the function (axis = 1 means over rows)
new_df = df.apply(multiply_coef, axis=1)
print(new_df)
# reaction product 0.5 1.0 1.5 2.0 ... 37.5 38.0 38.5 39.0 39.5 40.0
# 0 155Gd-p 062150.tot 0.0 0.0 0.0 0.0 ... 2.535995e-03 0.002747 0.002944 0.003127 0.003298 0.003454
# 1 155Gd-p 065156.L00 0.0 0.0 0.0 0.0 ... 2.495236e-02 0.024864 0.024262 0.022767 0.024261 0.024523
# 2 155Gd-p 063149.tot 0.0 0.0 0.0 0.0 ... 1.531474e+00 1.623678 1.712271 1.771160 1.821732 1.837864
# 3 155Gd-p 061146.tot 0.0 0.0 0.0 0.0 ... 0.000000e+00 0.000000 0.000000 0.000000 0.000000 0.000141
# 4 155Gd-p 061147.tot 0.0 0.0 0.0 0.0 ... 1.480000e-08 0.000157 0.000167 0.000174 0.000175 0.000173
# 5 155Gd-p 062151.tot 0.0 0.0 0.0 0.0 ... 1.683914e-04 0.000168 0.000167 0.000170 0.000169 0.000170
# 6 155Gd-p 063154.L00 0.0 0.0 0.0 0.0 ... 6.399416e-01 0.691611 0.735828 0.791352 0.837935 0.896896
# 7 155Gd-p 064150.tot 0.0 0.0 0.0 0.0 ... 5.102907e-03 0.008047 0.013453 0.021774 0.031468 0.042873
# 8 155Gd-p 064154.tot 0.0 0.0 0.0 0.0 ... 3.571862e+01 36.201836 35.838200 36.225368 35.891184 36.214268
# 9 155Gd-p 062148.tot 0.0 0.0 0.0 0.0 ... 0.000000e+00 0.000000 0.000000 0.000000 0.000174 0.000255
# 10 155Gd-p 061148.tot 0.0 0.0 0.0 0.0 ... 1.480000e-08 0.000009 0.000009 0.000009 0.000009 0.000009
# 11 155Gd-p 063153.tot 0.0 0.0 0.0 0.0 ... 6.211812e-01 0.675583 0.704795 0.732390 0.786614 0.821339
# 12 155Gd-p 063152.tot 0.0 0.0 0.0 0.0 ... 4.171750e-01 0.439857 0.471914 0.505691 0.539951 0.574934
# 13 155Gd-p 065151.tot 0.0 0.0 0.0 0.0 ... 3.771558e+01 45.089532 51.819980 58.753336 64.702344 70.283720
# 14 155Gd-p 063150.L01 0.0 0.0 0.0 0.0 ... 3.213435e-01 0.315979 0.308836 0.298603 0.292996 0.289710
# 15 155Gd-p 065152.tot 0.0 0.0 0.0 0.0 ... 8.954577e+01 81.778288 74.814444 66.918348 60.608664 54.227940