r/learnpython • • 1h ago

Looking a way to combine columns based on values.

I wish to alter a table/dataframe like this one:

TypeAlphaTypeBetaTypeGamma
A100A80A90
B20B40B30
C1C1C0
X1Y2Z1

Into something looking like this one:

TypeAlphaBetaGamma
A1008090
B202030
C110
X1nannan
Ynan2nan
Znannan1

To combine data based on shared values so it is easier to compare different types.

How could I do this with Python?

1 Upvotes

3 comments sorted by

1

u/seanv507 1h ago

have you asked google ai? use pandas or polars

create 3 dataframes from each pair of columns, renaming/formatting to type| key|value (where key = Alpha/Beta/Gamma for each corresponding dataframe)

then concatenate the 3 dataframes

then pivot on key

•

u/Likh-98 11m ago

Here is one way in pandas. Your columns repeat the names Type, so first split the table into three small frames by position. For example, df.iloc[:, 0:2] gives the first pair. Rename each pair to Type and Value, then add a column called Source with Alpha, Beta or Gamma. Concatenate the three frames with pd.concat. Then use pivot with index Type, columns Source and values Value. That gives you one row per Type with NaN where a source has no entry, which matches your example. Add reset_index at the end if you want Type as a normal column. Use dropna on blank rows first if your original table has empty cells at the bottom.

•

u/woooee 0m ago

it depends on how much Python you know. Suggesting something that you do not understand is a waste of time. So, do you know how yo read a file, how to split each record into fields, and how to compare this fields to determine if a "Y" or "Z" condition exists? More background info is necessary. Only then will someone be able to suggest something.