gpt4 book ai didi

python - 在 for 循环中使用 pandas 附加在新列中获取不需要的值

转载 作者:太空宇宙 更新时间:2023-11-03 20:46:17 24 4
gpt4 key购买 nike

我正在尝试制作一个脚本,该脚本循环遍历数据框中的行,并根据 C 列中的条件从 A 列或 B 列附加值来创建一个新列。但是,附加列中的行,因为我的新列包含多个值。

import pandas as pd
import numpy as np

#Loading in the csv file
filename = '35180_TRA_data.csv'
df1 = pd.read_csv(filename, sep=',', nrows=1300, skiprows=25, index_col=False, header=0)

#Calculating the B concentration using column A and a factor
B_calc = df1['A']*137.818

#The measured B concentration
B_measured = df1['B']

#Looping through the dataset, and append the B_calc values where the C column is 2, while appending the B_measured values where the C column is 1.
calculations = []

for row in df1['C']:
if row == 2:
calculations.append(B_calc)
if row ==1:
calculations.append(B_measured)

df1['B_new'] = calculations

我的新列 (B_new) 的值都是错误的。例如,在第一行中,它应该只是 0.00,但它包含许多值。所以附加部分出了问题。谁能发现这个问题?

最佳答案

B_calc 和 B_measured 是数组。因此,您必须指定要分配的值,否则您将分配整个数组。以下是您可以如何做到的:

df1 = pd.DataFrame({"A":[1,3,5,7,9], "B" : [9,7,5,3,1], "C":[1,2,1,2,1]})
#Calculating the B concentration using column A and a factor
B_calc = df1['A']*137.818

#The measured B concentration
B_measured = df1['B']
#Looping through the dataset, and append the B_calc values where the C column is 2, while appending the B_measured values where the C column is 1.
calculations = []

for index, row in df1.iterrows():
if row['C'] == 2:
calculations.append(B_calc[index])
if row['C'] ==1:
calculations.append(B_measured[index])

df1['B_new'] = calculations
<小时/>

但是迭代行是一个不好的做法,因为它需要很长时间。更好的方法是使用 pandas 掩码,其工作原理如下:

mask_1 = df1['C'] == 1
mask_2 = df1['C'] == 2

df1.loc[mask_1, 'C'] = df1[mask_1]['A']*137.818
df1.loc[mask_2, 'C'] = df1[mask_2]['B']

关于python - 在 for 循环中使用 pandas 附加在新列中获取不需要的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56580161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com