Python 将单个值从一列复制到满足条件的另一列

Python 将单个值从一列复制到满足条件的另一列,python,pandas,dataframe,Python,Pandas,Dataframe,我有以下数据帧(称之为df) 如果f_col超过一个阈值,我想获取col2中的匹配值并将其复制到col3 相同数据帧的理想示例为(如果阈值为125): 我试过使用f_col的面具,比如: mask = df.f_col > 125 column_name = 't_col' df.loc[mask, column_name] = 0 但这会导致一个错误,如下所示: AttributeError: 'int' object has no attribute 'iloc' 非常感谢您的帮助

我有以下数据帧(称之为df)

如果f_col超过一个阈值,我想获取col2中的匹配值并将其复制到col3

相同数据帧的理想示例为(如果阈值为125):

我试过使用f_col的面具,比如:

mask = df.f_col > 125
column_name = 't_col'
df.loc[mask, column_name] = 0
但这会导致一个错误,如下所示:

AttributeError: 'int' object has no attribute 'iloc'

非常感谢您的帮助。

您可以按照建议使用
loc
编写:

# Module import
import pandas as pd

# Cols names
col_over_treshold = "f_col"
col_to_copy = "s_col"
col_to_update = "t_col"

# Your dataFrame
df = pd.DataFrame([[10, 100, 0],
                   [20, 126, 0],
                   [65, 164, 0]],
                  columns=[col_over_treshold, col_to_copy, col_to_update])

# Your treshold
threshold = 125

# Process
df.loc[df[col_to_copy] > threshold, col_to_update] = df.s_col

#Show results
print(df)
#    f_col  s_col  t_col
# 0     10    100      0
# 1     20    126    126
# 2     65    164    164
或者可以定义一个函数,该函数的条件是将数据帧应用于:

# Your function to apply
def process(data):
    ret = 0
    if data[col_to_copy] > threshold:
        ret = data.s_col
    return ret


# Processing
df[col_to_update] = df.apply(process, axis=1)

#Show results
print(df)
#    f_col  s_col  t_col
# 0     10    100      0
# 1     20    126    126
# 2     65    164    164

那么你的意思是
df.loc[mask,column\u name]=0
?是的,我已经编辑了描述,第一种方法不能复制,列名可以是变量吗?当我将列名指定为变量时,会出现一个错误AttributeError:“DataFrame”对象没有属性“t_col”,请查看更新。我刚刚用代码中的变量替换了列名。这就是您的意思?部分是的,如果df.s_col中的
s_col
也是一个以变量表示的列名,该怎么办?或者这是不允许的?不可以,因为变量
col\u over\u treshold=“f\u col”
是一个字符串。
# Module import
import pandas as pd

# Cols names
col_over_treshold = "f_col"
col_to_copy = "s_col"
col_to_update = "t_col"

# Your dataFrame
df = pd.DataFrame([[10, 100, 0],
                   [20, 126, 0],
                   [65, 164, 0]],
                  columns=[col_over_treshold, col_to_copy, col_to_update])

# Your treshold
threshold = 125

# Process
df.loc[df[col_to_copy] > threshold, col_to_update] = df.s_col

#Show results
print(df)
#    f_col  s_col  t_col
# 0     10    100      0
# 1     20    126    126
# 2     65    164    164
# Your function to apply
def process(data):
    ret = 0
    if data[col_to_copy] > threshold:
        ret = data.s_col
    return ret


# Processing
df[col_to_update] = df.apply(process, axis=1)

#Show results
print(df)
#    f_col  s_col  t_col
# 0     10    100      0
# 1     20    126    126
# 2     65    164    164