Reputation: 133
I have a dataframe as below.
d={
'id' :[1,2,3,4,5],
'X1':[25,12,3,7,1],
'X2':[3,45,3,1,6],
'X3':[6,23,9,3,2]
}
df=pd.DataFrame(d, columns=['id','X1','X2','X3'])
looks like this:
I want to add a need column as X4. But I want to use column name and its value as below. How to use column name as a variable?
Expected X4 value for first raw:
X1:25,X2:3,X3:6
Upvotes: 1
Views: 583
Reputation: 1804
A different general approach:
def get_other_cols_vals(df1):
vals = []
for i_enm, col in enumerate(df1.columns):
vals.append(f"{col}:{df1.iloc[0, i_enm]}")
return ",".join(vals)
df['X4'] = df.groupby(df.index)[df.columns.drop('id').values].apply(get_other_cols_vals)
Upvotes: 1
Reputation: 8564
This should do:
df['X4'] = 'X1:' + df['X1'].astype(str) + ',X2:' + df['X2'].astype(str) + ',X3:' + df['X3'].astype(str)
gives
id X1 X2 X3 X4
0 1 25 3 6 X1:25,X2:3,X3:6
1 2 12 45 23 X1:12,X2:45,X3:23
2 3 3 3 9 X1:3,X2:3,X3:9
3 4 7 1 3 X1:7,X2:1,X3:3
4 5 1 6 2 X1:1,X2:6,X3:2
A more general and dynamic solution where you can just specify a list of columns as an argument to df[...].apply()
:
df['X4'] = df[['X1', 'X2', 'X3']].apply(
lambda x: ','.join(df.columns[x.name+1] + x.astype(str)), axis=1
)
Upvotes: 2
Reputation: 16147
d={
'id' :[1,2,3,4,5],
'X1':[25,12,3,7,1],
'X2':[3,45,3,1,6],
'X3':[6,23,9,3,2]
}
df=pd.DataFrame(d, columns=['id','X1','X2','X3'])
cols = [col for col in df.columns if 'X' in col]
df['X4'] = df[cols].apply(lambda x: ';'.join([str(x)+":"+str(y) for x,y in zip(cols,x.values)]), axis=1)
Output
id X1 X2 X3 X4
0 1 25 3 6 X1:25;X2:3;X3:6
1 2 12 45 23 X1:12;X2:45;X3:23
2 3 3 3 9 X1:3;X2:3;X3:9
3 4 7 1 3 X1:7;X2:1;X3:3
4 5 1 6 2 X1:1;X2:6;X3:2
Upvotes: 2
Reputation: 31146
Create a new column X4
that is the composition you want.
d={
'id' :[1,2,3,4,5],
'X1':[25,12,3,7,1],
'X2':[3,45,3,1,6],
'X3':[6,23,9,3,2]
}
df=pd.DataFrame(d, columns=['id','X1','X2','X3'])
df = df.assign(X4=lambda dfa: "X1:" + dfa["X1"].astype("string")
+ ",X2:" + dfa['X2'].astype("string")
+ ",X3:" + dfa['X3'].astype("string")
)
id X1 X2 X3 X4
1 25 3 6 X1:25,X2:3,X3:6
2 12 45 23 X1:12,X2:45,X3:23
3 3 3 9 X1:3,X2:3,X3:9
4 7 1 3 X1:7,X2:1,X3:3
5 1 6 2 X1:1,X2:6,X3:2
Upvotes: 2