我有一个数据帧,看起来像这样:
Fruit Cost Quantity Fruit_Copy
Apple 0.5 6 Watermelon
Orange 0.3 2 Orange
Apple 0.5 8 Apple
Apple 0.5 7 Apple
Banana 0.25 8 Banana
Banana 0.25 7 Banana
Apple 0.5 6 Apple
Apple 0.5 3 Apple我想要编写一个代码片段,在pandas中比较Fruit和Match,并输出一个新的列"Match“,该列指示Fruit = Fruit_Copy中的值。
提前感谢!
发布于 2020-02-07 04:02:14
像这样的东西会起作用的。
df.loc[df['Fruit'] == df['Fruit_Copy'], 'Match'] = 'Yes'df['Match'] = np.where(df['Fruit'] == df['Fruit_Copy'], 'Yes', 'No')发布于 2020-02-07 05:01:46
假设你的数据帧是“水果”。然后你可以使用熊猫系列等于函数pd.Series.eq as,
fruits['Match'] = pd.Series.eq(fruits['Fruit'],fruits['Fruit_Copy'])发布于 2020-02-07 04:09:19
您可以尝试如下所示:
import pandas as pd
import numpy as np
fruits = pd.DataFrame({'Fruit':['Apple', 'Orange', 'Apple', 'Apple', 'Banana', 'Banana', 'Apple', 'Apple'], 'Cost':[0.5,0.3,0.5,0.5,0.25,0.25,0.5,0.5], 'Quantity':[6,2,8,7,8,7,6,3], 'Fruit_Copy':['Watermelon', 'Orange', 'Apple', 'Apple', 'Banana', 'Banana', 'Apple', 'Apple']})
fruits['Match'] = np.where(fruits['Fruit'] == fruits['Fruit_Copy'], 1, 0)
fruits
Fruit Cost Quantity Fruit_Copy Match
0 Apple 0.50 6 Watermelon 0
1 Orange 0.30 2 Orange 1
2 Apple 0.50 8 Apple 1
3 Apple 0.50 7 Apple 1
4 Banana 0.25 8 Banana 1
5 Banana 0.25 7 Banana 1
6 Apple 0.50 6 Apple 1
7 Apple 0.50 3 Apple 1https://stackoverflow.com/questions/60102571
复制相似问题