如何使用python获取下一列的值?

2024-04-23 10:04:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据集,需要在其中匹配列a并在下一列B中获取其对应的下一个值。 例如,我必须检查A列中的1是否匹配,如果为真,则打印“第一页”

类似地,A列中的所有值都必须与X匹配,如果为真,则在B列中打印其下一个值

例如:

Example csv


Tags: 数据
1条回答
网友
1楼 · 发布于 2024-04-23 10:04:20

通过使用df.iloc,您可以通过索引获得所需的行或列。 通过使用mask,您可以过滤数据帧以获得所需的行(其中列a==某个值),并通过df.iloc[0,1]获取第二列中的值

import pandas as pd
d = {'col1': [1, 2,3,4], 'col2': [4,3,2,1]}
df = pd.DataFrame(data=d)
df

    col1    col2
0   1       4
1   2       3
2   3       2
3   4       1

# a is the value in the first column and df is the data frame
def a2b(a,df):
    return df[df.iloc[:,0]==a].iloc[0,1]
a2b(2,df)

返回3

相关问题 更多 >