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

时间:2019-05-08 22:30:35

标签: python pandas dataframe

我有以下数据框(称为df)。

f_col s_col t_col
10   100  0
20   126  0
65   164  0

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

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

f_col s_col t_col
10   100  0
20   126  126
65   164  164

我曾尝试使用f_col的掩码,如下所示:

mask = df.f_col > 125
column_name = 't_col'
df.loc[mask, column_name] = 0

但这会引发错误,就像这样:

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

任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:3)

您可以按照建议使用 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
相关问题