Home > Mobile >  Convert matrix to Dataframe with three columns
Convert matrix to Dataframe with three columns

Time:06-01

I have two Dataframes ( 'x' and 'y'), that define a grid (or coordinates) and a third Dataframe with the respective values ('z'). They are a result of an 2D interpolation.

import pandas as pd

df_x = pd.DataFrame(["a", "b", "c"])
df_y = pd.DataFrame(["alpha", "beta", "gamma"])
df_z = pd.DataFrame([1, 2, 3, 4, 5, 6,...9])

To continue, I would like to merge all the data in one Dataframe with the following (more like a database-like) structure:

df_new = pd.DataFrame({'x': ["a", "a", "a", "b", "b", "b", "c", "c", "c"], 'y': ["alpha", "beta", "gamma", "alpha", "beta", "gamma", "alpha", "beta", "gamma"], 'z': [1,2,3,4,5,6,7,8,9]})
x y z
a alpha 1
a beta 2
a gamma 3
b alpha 4
b beta 5
b gamma 6
c alpha 7
c beta 8
c gamma 9

There must be an easy way to rearrange the Dataframes, right? And what would be a good tag for this kind of question (without, searching is not very rewarding)?

Thank you very much :)

Ps.: I found some answers for R, but none for Python, yet.

CodePudding user response:

Check with merge

out = df_x.merge(df_y,how='cross').join(df_z)
  • Related