1

I have a Dataframe like this:

data = {'TYPE':['X', 'Y', 'Z'],'A': [11,12,13], 'B':[21,22,23], 'C':[31,32,34]}
df = pd.DataFrame(data)

    TYPE  A   B   C
0   X     11  21  31
1   Y     12  22  32
2   Z     13  23  34

I like to get the following DataFrame:

    TYPE  A   A_added  B   B_added  C   C_added
0   X     11  15       21  25       31  35
1   Y     12  18       22  28       32  38
2   Z     13  20       23  30       34  40

For each column (next to TYPE column), here A,B,C:

  • add a new column with the name column_name_added

  • if TYPE = X add 4, if TYPE = Y add 6, if Z add 7

1 Answer 1

3

Idea is multiple values by helper Series created by Series.map with dictionary with DataFrame.add, add to original by DataFrame.join and last change order of columns by DataFrame.reindex:

d = {'X':4,'Y':6, 'Z':7}
cols = df.columns[:1].tolist() + [i for x in df.columns[1:] for i in (x, x + '_added')]
df1 = df.iloc[:, 1:].add(df['TYPE'].map(d), axis=0, fill_value=0).add_suffix('_added')
df2 = df.join(df1).reindex(cols, axis=1)
print (df2)
  TYPE   A  A_added   B  B_added   C  C_added
0    X  11       15  21       25  31       35
1    Y  12       18  22       28  32       38
2    Z  13       20  23       30  34       41

EDIT: For values not matched dictionary are created missing values, so if add Series.fillna it return value 7 for all another values:

d = {'X':4,'Y':6}
cols = df.columns[:1].tolist() + [i for x in df.columns[1:] for i in (x, x + '_added')]
df1 = df.iloc[:, 1:].add(df['TYPE'].map(d).fillna(7).astype(int), axis=0).add_suffix('_added')
df2 = df.join(df1).reindex(cols, axis=1)
print (df2)
  TYPE   A  A_added   B  B_added   C  C_added
0    X  11       15  21       25  31       35
1    Y  12       18  22       28  32       38
2    Z  13       20  23       30  34       41
2
  • 1
    very nice, thx! If i have more rows and for every row x add 4, for y add 6, for every other add 7. Without defining the dictionary with every value. Is there a solution?
    – Paul
    Commented Feb 26, 2020 at 15:27
  • 1
    @anky_91 - Yop, I agree, but I like more general solutions, so .pivot(*d) shoiuld failed if more like 3 columns, so I donet use it.
    – jezrael
    Commented Feb 27, 2020 at 6:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.