[英]Python Compare 2 Columns And Write A 4th Column With Values From 3rd Column (pandas )
Python Compare 2 Columns And Write A 4th Column With Values From 3rd Column If Column 1 Matches Column 2. I have Two sheets in excel. Python 比较 2 列,如果第 1 列与第 2 列匹配,则用第 3 列中的值写入第 4 列。我在 excel 中有两张纸。 First Sheet looks like sheet1 second sheets looks like Sheet2 .第一张表看起来像sheet1第二张表看起来像Sheet2 。
I need to convert this formula into pandas formula.我需要将此公式转换为 pandas 公式。 The formula which generate etype is生成 etype 的公式是
=IFERROR(INDEX(Sheet2!A:B,MATCH(Sheet1!A3,Sheet2!A:A,0),2),"herbs").
I think your question is still slightly confusing but I hope I am getting this correctly.我认为你的问题仍然有点令人困惑,但我希望我能正确理解这一点。 Your idea is that you would like to compare a list of items that can either be fruit or herbs, and you have a list of fruits.您的想法是,您想比较一个可以是水果或草药的项目列表,并且您有一个水果列表。
Using the list of fruits, you would like to then check it against your list of items to return the etype
which should be a fruit
if it matches any item in the list of fruits or herb
otherwise.使用水果列表,然后您希望将其与您的项目列表进行检查,以返回应该是fruit
的etype
,如果它与水果或herb
列表中的任何项目匹配的话。
If I am correct, you may refer to this suggested code below:如果我是正确的,您可以参考以下建议的代码:
import pandas as pd
# Importing your data with pandas
main_df = pd.read_csv(filename, sheetname = 'Sheet1') # Sheet 1 should be all items
fruits_df = pd.read_csv(filename, sheetname = 'Sheet2') # fruits sheet
# Convert your fruits into a list since we know they are all fruits
fruit_lst = fruits_df['fruits'].tolist()
# Iterate through your main list of items and check if they are a fruit
for i in range(len(main_df)):
# Update 'herb' -> 'fruit' if it matches
if main_df['herbs'][i] in fruit_lst:
main_df['etype'][i] = 'fruit'
Generating some samples from your screenshots, this is what the code should return.从您的屏幕截图中生成一些示例,这就是代码应该返回的内容。
Before, the dataframe would look something like this:之前,dataframe 看起来像这样:
After the check against the fruit list, you should get the result you are looking for:核对水果清单后,您应该得到您正在寻找的结果:
Hope this helps, though do try to share clearer details/screenshots in the future as well to help others understand your question!希望这会有所帮助,但请尝试在未来分享更清晰的细节/屏幕截图,以帮助其他人理解您的问题!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.