2017-07-19 68 views
7

我有以下的數據幀DF:基於頭Python的熊貓匹配VLOOKUP列中的值

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 

我想查找他們加入郵件列表在今年顧客的價值,並將其保存在一個新專欄。

輸出將是:

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

我已經找到了比賽VLOOKUP在python一些解決方案,但沒有說會用其他列的標題。

+1

查找是列2015,2016和2017年 – jeangelj

回答

12

使用pd.DataFrame.lookup
請記住,我假設Customer_ID是索引。

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

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

df.assign(
    Purchases_1st_year=df.lookup(df.index, df.Year_joined_mailing) 
) 

      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 

但是,你必須要小心在第一年列的列名和整數比較可能的串...

核選項,以確保類型比較受到尊重。

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 
+0

哇!我仍然在想'熔化',但你明白了! +1 – Wen

+0

魔法......並不認爲這是可能的一行 - 謝謝 – jeangelj

+0

不客氣! – piRSquared

2

你可以申請「應用」到每一行

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

謝謝 - 這也起作用了!我高舉了它 – jeangelj

1

我會做這樣的,假設表頭和Year_joined_mailing是相同的數據類型和所有Year_joined_mailing值都是有效的列。如果數據類型不相同,則可以在適當的位置添加str()int()進行轉換。

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

我們這裏所做的是迭代的數據幀索引來獲取該指數的'Year_joined_mailing'場,然後使用該得到我們想要的列,並再次從列中選擇該索引,推這一切的列表,並給我們的新列指派該'Year_joined_mailing'

如果您'Year_joined_mailing'列不會永遠是一個有效的列名,然後嘗試:

from numpy import nan 
new_col = [] 
for i in df.index: 
    try: 
     new_col.append(df[df['Year_joined_mailing'][i]][i]) 
    except IndexError: 
     new_col.append(nan) #or whatever null value you want here) 
df['Purchases_1st_year'] = new_col 

這更長的代碼片段艾科製作相同的東西,但不會破壞,如果'Year_joined_mailing'不在df.columns

+0

非常感謝 - 這工作得很好;所以我選了它 – jeangelj