Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用for循环在dataframe中现有列的基础上创建新列_Python_Pandas_Loops_For Loop_Dataframe - Fatal编程技术网

Python 如何使用for循环在dataframe中现有列的基础上创建新列

Python 如何使用for循环在dataframe中现有列的基础上创建新列,python,pandas,loops,for-loop,dataframe,Python,Pandas,Loops,For Loop,Dataframe,我有一个包含两列的数据集,我想创建第三列,说明前两列的值是否相同,并为每一行命名相同的值 示例数据: 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'],

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

示例数据:

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 
i、 e.添加一个新列,首先说明颜色_1和颜色_2列何时匹配,然后说明共享值(红色、蓝色或绿色)

到目前为止,我的方法是在COLOR_1和COLOR_2列匹配时创建布尔数组的有序dict,我希望随后创建一个循环,以迭代方式: 1.将布尔数组的“True”更改为匹配的值,即红色、蓝色或绿色,以及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.我不知道如何更改循环中布尔数组的值,以便有条件地将“True”替换为两个颜色列(红色、蓝色或绿色)的共享值。 2.“我的循环”当前会覆盖每个循环中的成对匹配,因此先前颜色匹配(红色和蓝色)的匹配行信息将丢失,并且只显示绿色。我希望最终得到三列成对匹配(即每次循环运行时添加/追加列),然后将它们合并到我想要的单个列中。 非常感谢

使用布尔掩码比较两列:

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
与两列比较的布尔掩码一起使用:

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

更简单的方法可能是:

df1["Pairwise_match"] = False
df1.loc[df1.Colour_1 == df1.Colour_2, "Pairwise_match"] = df1.Colour_1[df1.Colour_1 == df1.Colour_2]

这将创建一个充满False的列,然后在列之间颜色匹配的地方,用颜色值替换它们。更简单的方法可能是:

df1["Pairwise_match"] = False
df1.loc[df1.Colour_1 == df1.Colour_2, "Pairwise_match"] = df1.Colour_1[df1.Colour_1 == df1.Colour_2]

这将创建一个充满假的列,然后在列之间颜色匹配的地方,用颜色值替换它们

我认为这个解决方案比我的更优雅+1@jezrael这比我正在做的工作更出色、更优雅——非常感谢!我认为这个解决方案比我的更优雅+1@jezrael这比我正在做的工作更出色、更优雅——非常感谢!