I would do it this way, assuming that the column headers and Year_joined_mailing are the same data type and that all Year_joined_mailing values ββare valid columns. If the data types do not match, you can convert them by adding str() or int() where necessary.
df['Purchases_1st_year'] = [df[df['Year_joined_mailing'][i]][i] for i in df.index]
What we are doing here is iterating over the indices in the dataframe to get the 'Year_joined_mailing' field for that index, then using it to get the column you want and again selecting that index from the column, clicking everything in the list and assigning it to our new column 'Year_joined_mailing'
If your column 'Year_joined_mailing' not always the correct column name, try:
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
This longer piece of code does the same thing, but does not 'Year_joined_mailing' if 'Year_joined_mailing' not in df.columns
Jeremy barnes
source share