Paul
Paul

Reputation: 326

Add columns - specify name - row value based on other

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:

Upvotes: 1

Views: 50

Answers (1)

jezrael
jezrael

Reputation: 863301

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

Upvotes: 3

Related Questions