熊猫基于匹配值

时间:2020-09-16 07:11:05

标签: python-3.x pandas string-matching

在具有5列的csv文件中,如果存在与该列相关的特定字符串匹配,我试图在2列之一中复制一个值。

首先,csv文件如下所示

# 'Test.csv'

col1    col2    col3    col4    col5
alex    str1    47  0   54
beth    str2    94  94  0
stan    str1    18  0   18
hank    str1    37  0   37
june    str1    84  0   84
mary    str2    34  34  0

简单地说,

如果'col2'的值为'str1',则只有'col4'的值为'col3',
(要么) 如果'col2'的值为'str2',则只有'col5'的值为'col3'。

似乎很接近我的答案的代码位于此article中,但是我无法为上面的数据进行修改。

Copy value from one column based on the value of another column

2 个答案:

答案 0 :(得分:1)

您可能需要两行代码:

df['col4'] = np.where(df.col2 == 'str1', df.col3, df.col4)
df['col5'] = np.where(df.col2 == 'str2', df.col3, df.col5)

答案 1 :(得分:0)

使用:

df_copy.loc[df_copy['col2']=='str1', 'col4'] = df_copy['col3']    
df_copy.loc[df_copy['col2']=='str2', 'col5'] = df_copy['col3']

这意味着如果匹配条件,则通过列col4的值设置col5col3