Python Pandas根据头值匹配Vlookup列

2024-05-29 06:05:01 发布

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

我有以下数据帧df:

Customer_ID | 2015 | 2016 |2017 | Year_joined_mailing
ABC            5      6     10     2015
BCD            6      7     3      2016        
DEF            10     4     5      2017
GHI            8      7     10     2016

我想查找客户在加入邮件列表的那一年的价值,并将其保存在新的列中。在

输出将是:

^{pr2}$

我在python中找到了一些匹配vlookup的解决方案,但是没有一个会使用其他列的头。在


Tags: 数据iddf列表客户def邮件customer
3条回答

我会这样做,假设列标题和Year_joined_mailing是相同的数据类型,并且所有Year_joined_mailing值都是有效的列。如果数据类型不同,可以通过在适当的地方添加str()或{}来转换它。在

df['Purchases_1st_year'] = [df[df['Year_joined_mailing'][i]][i] for i in df.index]

我们在这里所做的是迭代dataframe中的索引,以获得该索引的'Year_joined_mailing'字段,然后使用该字段来获得所需的列,再次从列中选择该索引,将其全部推送到一个列表中,并将其分配给新列'Year_joined_mailing'

如果您的'Year_joined_mailing'列不总是有效的列名,请尝试:

^{pr2}$

这个较长的代码片段完成了相同的任务,但是如果'Year_joined_mailing'不在df.columns中,则不会中断

您可以对每一行应用“应用”

df.apply(lambda x: x[x['Year_joined_mailing']],axis=1)

使用^{}
请记住,我假设Customer_ID是索引。在

df.lookup(df.index, df.Year_joined_mailing)

array([5, 7, 5, 7])

^{pr2}$

但是,在比较列名中可能的字符串和第一年列中的整数时必须小心。。。在

核选择,以确保类型比较得到尊重。在

df.assign(
    Purchases_1st_year=df.rename(columns=str).lookup(
        df.index, df.Year_joined_mailing.astype(str)
    )
)

             2015  2016  2017  Year_joined_mailing  Purchases_1st_year
Customer_ID                                                           
ABC             5     6    10                 2015                   5
BCD             6     7     3                 2016                   7
DEF            10     4     5                 2017                   5
GHI             8     7    10                 2016                   7

相关问题 更多 >

    热门问题