Skip to main content
 首页 » 编程设计

python之如何使用 for 循环以 pandas 数据框中现有列为条件创建新列

2025年05月04日20lovecherry

我有一个包含两列的数据集,我想创建第三列来说明前两列的值是否相同,并为每一行命名相同的值。

示例数据:

import pandas as pd 
 
data = {'Colour_mix': ['1','2', '3', '4', '5', '6', '7', '8', '9', '10'],  
        'Colour_1': ['red', 'blue', 'red', 'red', 'green', 'green', 'green', 'red', 'blue', 'blue'], 
        'Colour_2': ['red', 'green', 'red', 'blue', 'green', 'red', 'green', 'red', 'green', 'blue'] } 
df1 = pd.DataFrame(data) 
cols = ['Colour_mix', 'Colour_1', 'Colour_2'] 
df1 = df1[cols]  
df1 

我想要的结果看起来像这样:

data2 = {'Colour_mix': ['1','2', '3', '4', '5', '6', '7', '8', '9', '10'],  
        'Colour_1': ['red', 'blue', 'red', 'red', 'green', 'green', 'green', 'red', 'blue', 'blue'], 
        'Colour_2': ['red', 'green', 'red', 'blue', 'green', 'red', 'green', 'red', 'green', 'blue'], 
        'Pairwise_match': ['red', 'False', 'red', 'False', 'green', 'False', 'green', 'red', 'False', 'blue']} 
df2 = pd.DataFrame(data2) 
cols2 = ['Colour_mix', 'Colour_1', 'Colour_2', 'Pairwise_match'] 
df2 = df2[cols2]  
df2  

即添加了一个新列,其中首先说明 Colour_1 和 Colour_2 列何时匹配,其次说明共享值是什么(红色、蓝色或绿色)。

到目前为止,我的方法是为 Colour_1 和 Colour_2 列匹配时创建一个有序的 bool 数组字典,然后我希望创建一个迭代循环: 1. 将 bool 数组的“真”更改为匹配项的值,即红色、蓝色或绿色,以及 2. 将结果匹配项合并到一个列中。

到目前为止我的代码:

# Create a list of boolean arrays for each match pair 
colour_matches = collections.OrderedDict() 
 
colour_matches['red'] = ( (df1['Colour_1']=='red') 
                      & (df1['Colour_2']=='red') 
                      ) 
 
colour_matches['blue'] = ( (df1['Colour_1']=='blue') 
                      & (df1['Colour_2']=='blue') 
                      ) 
 
colour_matches['green'] = ( (df1['Colour_1']=='green') 
                      & (df1['Colour_2']=='green') 
                      ) 
 
# Add pairwise match columns 
 
for p in colour_matches: 
    print(p) 
    _matches_df = pd.DataFrame(colour_matches[p]) 
    _matches_df.columns = ['Pairwise_match'] 
    df_new = pd.concat([df1, _matches_df], axis=1) 

我有两个问题: 1. 我不知道如何在循环中更改 bool 数组的值,因此“True”被有条件地替换为两个颜色列(红色、蓝色或绿色)的共享值。 2. 我的循环目前覆盖了每个循环中的 Pairwise_match,因此关于先前颜色匹配(红色和蓝色)的匹配行的信息丢失并且它只显示绿色。我希望最终得到三列成对匹配(即在每次循环运行时添加/附加列),然后我可以将它们合并到我想要的单个列中。 非常感谢。

请您参考如下方法:

使用numpy.where使用 bool 掩码比较两列:

df1['Pairwise_match'] = np.where(df1['Colour_1'] == df1['Colour_2'], df1['Colour_1'], False) 
print (df1) 
  Colour_mix Colour_1 Colour_2 Pairwise_match 
0          1      red      red            red 
1          2     blue    green          False 
2          3      red      red            red 
3          4      red     blue          False 
4          5    green    green          green 
5          6    green      red          False 
6          7    green    green          green 
7          8      red      red            red 
8          9     blue    green          False 
9         10     blue     blue           blue 

详细信息:

print (df1['Colour_1'] == df1['Colour_2']) 
0     True 
1    False 
2     True 
3    False 
4     True 
5    False 
6     True 
7     True 
8    False 
9     True 
dtype: bool