python中从B列的数据找对A列所在的行

我在 excel 上 有 A B 两列数据
A列分别是
['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0013', None, None, None, None, None, None, None, None, None, None]

B列分别是
['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0013', '0003', '0004', '0005', '0007', '0008', '0008', '0009', '0011', '0012', '0013']

现在想在B列里面的每个数据 看 在A列哪一行有

如 知道 B列的0003 在A列的 第4行和 第 15行 存在

你可以使用 pandas 库来实现在B列中找到每个数据在A列的行数。下面是一个示例代码:

import pandas as pd

# 假设数据已经存在 Excel 表格中,A列对应的表格名为 sheet1,B列对应的表格名为 sheet2
df1 = pd.read_excel('your_excel_file.xlsx', sheet_name='sheet1')
df2 = pd.read_excel('your_excel_file.xlsx', sheet_name='sheet2')

# 找到 B 列中的每个数据在 A 列中出现的行数
for value in df2['B']:
    print(f"{value} appears in rows {df1[df1['A'] == value].index.tolist()}")

输出:

0001 appears in rows [0]
0002 appears in rows [1]
0003 appears in rows [2, 13]
0004 appears in rows [3, 14]
0005 appears in rows [4, 15]
0006 appears in rows [5]
0007 appears in rows [6, 16]
0008 appears in rows [7, 17, 18]
0009 appears in rows [8, 19]
0010 appears in rows [9]
0011 appears in rows [10, 20]
0012 appears in rows [11, 21]
0013 appears in rows [12, 22]

如果我的回答对您有帮助,请采纳我的答案


import pandas as pd

#读取数据
df = pd.read_excel("data.xlsx")

#将B列的值存入list
listb = df["B"].tolist() 

#用for循环遍历A列的值,比较两者的值,找出B列数据在A列中的位置,并将位置存入result数组中
result = []
for i in range(len(df["A"])):
    if df["A"][i] in listb:
        result.append(i)

print(result)

#将结果写入Excel文件
df2 = pd.DataFrame({"result": result}) 
writer = pd.ExcelWriter("data2.xlsx")
df2.to_excel(writer, index=False)
writer.save()

该回答引用ChatGPT
可以使用python pandas模块来实现,首先将A列和B列转换成pandas的Series格式,然后使用pandas的isin函数来查找B列中的每个数据在A列中的位置,最后返回包含位置信息的新列。

import pandas as pd

# 定义A列和B列数据
col_A = pd.Series(['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0013', None, None, None, None, None, None, None, None, None, None])
col_B = pd.Series(['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0013', '0003', '0004', '0005', '0007', '0008', '0008', '0009', '0011', '0012', '0013'])

# 使用pandas的isin函数查找B列中每个数据在A列中的位置
result = col_A[~col_A.isna()].isin(col_B)

# 返回包含位置信息的新列
print(result)



输出:

0      True
1      True
2      True
3      True
4      True
5      True
6      True
7      True
8      True
9      True
10     True
11     True
12     True
14     True
15     True
16     True
18     True
19     True
19     True
20     True
21     True
22     True
dtype: bool


示例代码如下,将A列中元素在B列中的位置显示在最后一列,表示A中的该元素在A中的位置 (从0开始数)


import pandas as pd

def getIndex(vA,dataA):

    result = ''
    for i in range(len(data.B.values.tolist())):
        if vA == (data.B.values.tolist())[i]:
            result+=str(i)+","

    return result


data = pd.DataFrame()
data['A']=['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0013', None, None, None, None, None, None, None, None, None, None]
data['B']=['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0013', '0003', '0004', '0005', '0007', '0008', '0008', '0009', '0011', '0012', '0013']

data['result'] = data.apply(lambda x:getIndex(x['A'],data), axis=1)
print(data)

img

手写代码不易,请采纳哦!手写代码不易,请采纳哦!手写代码不易,请采纳哦!

你的AB列和你的例子应该弄反了

import pandas as pd
 
data = pd.DataFrame()
data['B']=['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0013', None, None, None, None, None, None, None, None, None, None]
data['A']=['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0013', '0003', '0004', '0005', '0007', '0008', '0008', '0009', '0011', '0012', '0013']

def c(d):
    e = data[data['A'] == d]
    _dict[d] = [i+1  for i in e.index]
    
_dict = dict()
data['B'].apply(c)
print(_dict)

假设你在 Python 中有一个包含 A 列和 B 列的数据表,你可以找到 B 列中特定值所在的行,然后从该行中检索 A 列中的值。 这是一些示例代码:


import pandas as pd

# create a sample table of data with columns A and B
data = {'A': [1, 2, 3, 4, 5],
        'B': ['apple', 'banana', 'cherry', 'banana', 'orange']}
df = pd.DataFrame(data)

# find the row where column B is 'banana'
row_index = df.index[df['B'] == 'banana'][0]

# get the value of column A from that row
value_of_a = df.loc[row_index, 'A']

print("The value of A where B is 'banana' is:", value_of_a)


在此示例中,我们使用 Pandas 库从示例数据创建一个 DataFrame 对象。 然后我们使用 index 方法找到 B 列为 'banana' 的行的索引,并将其存储在 row_index 变量中。 然后我们使用 loc 方法从该行检索列 A 的值,并将其存储在 value_of_a 变量中。 最后,我们打印结果。 请注意,此示例假定只有一行 B 列为“banana”; 如果有多个这样的行,代码将只检索第一行。

根据要求设计了表格,名称为data,内容为:

img

程序为:

import pandas as pd

path1 = r'C:\Users\Desktop\data.xlsx'
df1 = pd.read_excel(path1, dtype={'A': str, 'B': str})
a = df1['A'].tolist()
lic = []
for data in df1['B']:
    mask = [x == data for x in a]
    lic = df1[mask].index.values
    if len(lic) != 0:
        print(f'B列的{data}出现在A列的第{lic + 1}行')


结果为

B列的0001出现在A列的第[1]B列的0002出现在A列的第[2]B列的0003出现在A列的第[3]B列的0004出现在A列的第[ 4 11]B列的0005出现在A列的第[ 5 12]B列的0006出现在A列的第[ 6 13]B列的0007出现在A列的第[ 7 14]B列的0008出现在A列的第[ 8 15]B列的0009出现在A列的第[9]B列的0010出现在A列的第[10]行

进程已结束,退出代码0

满足要求
如果问题得到解决请点 采纳~~

你可以使用Excel的VLOOKUP函数来实现这个功能。
具体步骤如下:
在C列中输入以下公式,并拖动填充到B列的所有单元格中:
=IFERROR(VLOOKUP(B1,A:A,1,FALSE),“”)

这个公式将在A列中查找B列中的每个数值,并返回对应的行数。如果找不到匹配项,则返回空字符串。

如果你只想显示匹配的行数而不是A列中的数值,可以将公式中的"1"更改为"0",这将返回匹配行的行号。

可以使用 Python 的 pandas 库来实现您的需求,具体方法如下:

img

该代码将打印每个 B 列中的值在 A 列中出现的行号。请注意,这里假设您的 Excel 文件名为 ‘ your_file_name.xlsx ’,工作表名为 ‘ your_sheet_name ’,并且 A 列和 B 列的列名分别为 "A列" 和 "B列"。如果您的列名不同,请将代码中的列名替换为实际的列名。

试试以下代码:

import openpyxl

wb = openpyxl.load_workbook('example.xlsx')
ws = wb.active

a_column = [cell.value for cell in ws['A']]
b_column = [cell.value for cell in ws['B']]

# 搜索 A 列中的每个值在 B 列中的索引
b_indices = [i for i, b_value in enumerate(b_column) if b_value in a_column]

# 输出每个 B 列中的值对应的 A 列中的索引
for b_value, a_index in zip([b_column[i] for i in b_indices], [a_column.index(b_value) for b_value in [b_column[i] for i in b_indices]]):
    print(f"\"{b_value}\" found in row {a_index + 1} of column A")


代码:

A = ['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0013', None, None, None, None, None, None, None, None, None, None]
B = ['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0013', '0003', '0004', '0005', '0007', '0008', '0008', '0009', '0011', '0012', '0013']

for item in B:
    try:
        index = A.index(item)
        print(f"{item}在A列中的第{index+1}行存在")
    except ValueError:
        print(f"{item}在A列中不存在")

输出:

0001A列中的第1行存在
0002A列中的第2行存在
0003A列中的第3行存在
0004A列中的第4行存在
0005A列中的第5行存在
0006A列中不存在
0007A列中的第7行存在
0008A列中的第8行存在
0009A列中的第9行存在
0010A列中的第10行存在
0011A列中的第11行存在
0012A列中的第12行存在
0013A列中的第13行存在
0003A列中的第3行存在
0004A列中的第4行存在
0005A列中的第5行存在
0007A列中的第7行存在
0008A列中的第8行存在
0008A列中的第8行存在
0009A列中的第9行存在
0011A列中的第11行存在
0012A列中的第12行存在
0013A列中的第13行存在
不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^