I have a dataframe like so:
id variable value
1 x 5
1 y 5
2 x 7
2 y 7
Now for every row, I want to add a calculated row. This is what I am doing as of now:
a = 2
b = 5
c = 1
d = 3
df2 = pd.DataFrame(columns = ["id", "variable", "value"])
for index, row in df.iterrows():
if row['variable'] == 'x':
df2 = df2.append({'id':row['id'], 'variable':'x1', 'value':a*row['value']+b}, ignore_index=True)
else:
df2 = df2.append({'id':row['id'], 'variable':'y1', 'value':c*row['value']+d}, ignore_index=True)
df = pd.concat([df, df2])
df = df.sort_values(['id', 'variable'])
And so finally I get:
id variable value
1 x 5
1 x1 15
1 y 5
1 y1 8
2 x 7
2 x1 19
2 y 7
2 y1 10
But surely there must be a better way to do this. Perhaps where I could avoid for loop and sorting, as there are a lot of rows.