[英]How to lookup data in excel and return value next to it?
My Excel data:我的 Excel 数据:
What Im I doing?我在做什么?
I have been looking into pandas
, openpyxl
all sorts of modules.我一直在研究
pandas
, openpyxl
各种模块。 Not sure how to assemble a script to do me a vlookup()
function.不知道如何组装一个脚本来做一个 vlookup
vlookup()
function。
What I am trying to do is, give a variable of find_string = "John"
and use it to look inside the sheet and return me Last Name
connected on the same row as the First Name
of John
.我想要做的是,给出一个变量
find_string = "John"
并用它来查看工作表内部并返回我Last Name
与John
的First Name
连接在同一行上。
Example例子
find_string = "John"
return value of John = West
because John and West are on the same row but different column.因为约翰和韦斯特在同一行但在不同的列。
How can this be done?如何才能做到这一点?
This is what I got to..这就是我要..
import pandas as pd
file = 'C:/Users/user/Desktop/test/Excel file.xlsx'
find_string = "John"
x = pd.read_excel(file, sheet_name = 'Sheet2')
UPDATE FROM AN ANSWER Return value:从答案更新返回值:
file = 'C:/Users/user/Desktop/test/Excel file.xlsx'
df = pd.read_excel(file, sheet_name = 'sheet2')
new_df = df[df['First Name'].str.contains('John')][['Last Name']].reset_index(drop = True)
I need to return just the word West
我只需要返回
West
这个词
For this specific case, you can just use the pandas Series.str.contains().对于这种特定情况,您可以只使用 pandas Series.str.contains()。 The documentation is on this link https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html .
文档位于此链接https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html 上。 For your specific example, something like this could suffice.
对于您的具体示例,这样的事情就足够了。
file = 'C:/Users/user/Desktop/test/Excel file.xlsx'
df = pd.read_excel(file, sheet_name = 'sheet2')
new_df = df[df['First Name'].str.contains('John')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.