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

标签 python pandas

我正在尝试制作一个脚本,该脚本循环遍历数据框中的行,并根据 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/

相关文章:

python - 如何在 Flask 的页面上显示小部件?

python - pandas:合并多个数据帧以获得所需的多重索引时出现问题

python - 我们如何使用回调和提供数据框的函数动态地在 Dash Table 中创建数据列

matlab - 使用 h5py 保存 pandas DataFrame 以便与其他 hdf5 阅读器互操作

python - 使用带有关键字参数的 map() 函数

python - Selenium Chrome Headless 下载文件

python - 如何初始化需要 __new__ 和 __init__ 的对象

python - 将 PyArrow Parquet 加速到 Pandas 以获取具有大量字符串的数据帧

python - 如何通过检查行x+1-行x是否大于特定值来更改值(pandas)

python - 如果满足不同行中的条件,则替换数据框中的字符串