If I have a df:
df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c'])
and wish to take the second column "b" and append to the end of a "new" df with the columns "a" and "b" and a name column containing the name of the "b" column and then the third column "c" and append to the end of the new df together with "a" and the name "c" appened to the name column. It is timeseries data with a datetime in "a" and a variable in b and c and there is sometimes 20 variables and sometimes 1 or 2.
How do I do that in a pretty and efficient way. right now im doing it like this but have to do it a 100 times for slightly different df but with the same idea.
col_nam_list = list(df.columns.values)
df_1 = pd.DataFrame()
df_1["a"] = df["a"]
df_1["name"] = col_nam_list[1]
df_1["value"] = df["b"]
df_2 = pd.DataFrame()
df_2["a"] = df["a"]
df_2["name"] = col_nam_list[2]
df_2["value"] = df["c"]
result = pd.concat([df_1, df_2])
Now this is not fun to write and looks so ugly and unnecessary long. How do I improve my method?
BR