r/learnpython • • 9h 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?

EDIT: I followed Likh-98's advice but I ran into an issue.

import pandas as pd

df0=pd.read_csv('Table of Test.txt', sep='\t')
df1=df0.iloc[:,0:2]
df2=df0.iloc[:,2:4]
df3=df0.iloc[:,4:] #works

df1.rename(columns={'Alpha':'Value'}, inplace=True)
df2.rename(columns={'Type.1':'Type','Beta':'Value'}, inplace=True)
df3.rename(columns={'Type.2':'Type','Gamma':'Value'}, inplace=True)

df1=df1.assign(Source=['Alpha','Alpha','Alpha','Alpha']) #They were unclear how to fill the new column
df2=df2.assign(Source=['Beta','Beta','Beta','Beta'])
df3=df3.assign(Source=['Gamma','Gamma','Gamma','Gamma'])

frames=[df1, df2, df3]

result=pd.concat(frames)

result.pivot(index='Type', columns='Sourge', values='Value')

#Here I got "ValueError: Index contains duplicate entries, cannot reshape", when result was:

Type Value Sourge

0 A 100 Alpha

1 B 20

2 C 1

3 X 1

0 A 80 Beta

1 B 40

2 C 1

3 Y 2

0 A 90 Gamma

1 B 30

2 C 0

3 Z 1

4 Upvotes

22 comments sorted by

2

u/Likh-98 8h 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.

1

u/Dragoran21 4h ago

Do you mean rename the headers of dataframes as Type and Value?

1

u/Likh-98 3h ago

Yes, exactly. Each pair has its two columns called Type and something else, so after splitting with iloc, set the column names on each small frame to the same two names, for example df1.columns = ['Type', 'Value']. Doing that on all three frames is what lets pd.concat stack them into one long table instead of making six separate columns. After that you add the Source label and pivot. If your real header names differ, the names you pick just need to match across the three frames.

1

u/Dragoran21 4h ago

Can you describe the column Source more? Did you mean "every row is Alpha" or "only first row is Alpha and the rest are empty cells?"

1

u/Likh-98 3h ago

Good question. Source is just a label you create yourself, it is not in your original data. Every row in the first pair of columns gets the same value, Alpha, every row in the second pair gets Beta, and every row in the third gets Gamma. So after you rename the pair to Type and Value, do something like df1['Source'] = 'Alpha' on the first frame, df2['Source'] = 'Beta' on the second, and so on. That label is what pivot then turns into the Alpha, Beta and Gamma columns, so each Type ends up with one value per source in a single row.

1

u/Dragoran21 2h ago

I got to concat() part but something is wrong.

result=pd.concat(frames)
#result
Type  Value Sourge Type.1 Type.2
0    A    100  Alpha    NaN    NaN
1    B     20           NaN    NaN
2    C      1           NaN    NaN
3    X      1           NaN    NaN
0  NaN     80   Beta      A    NaN
1  NaN     40             B    NaN
2  NaN      1             C    NaN
3  NaN      2             Y    NaN
0  NaN     90  Gamma    NaN      A
1  NaN     30           NaN      B
2  NaN      0           NaN      C
3  NaN      1           NaN      Z
#Where did type.1 & type.2 come from? I cannot pivot() this.

1

u/Dragoran21 2h ago

Ok, I noticed that the Type columns were numbered when I split them.

Fixed that but got: "ValueError: Index contains duplicate entries, cannot reshape" when I ran the code

result.pivot(index='Type', columns='Source', values='Value')
#When result was:
  Type  Value Sourge
0    A    100  Alpha
1    B     20       
2    C      1       
3    X      1       
0    A     80   Beta
1    B     40       
2    C      1       
3    Y      2       
0    A     90  Gamma
1    B     30       
2    C      0       
3    Z      1  

•

u/Likh-98 59m ago

That error comes from the Source column. In your printed result the label only appears on the first row of each block and the other rows are blank, and the header is spelled Sourge, so pivot cannot find a Source column to spread. It also means A shows up several times with the same Source value, which is exactly what the duplicate entries message is complaining about. Set the label on the whole frame, not one cell, like df1['Source'] = 'Alpha' with the correct spelling, so every row in that block carries it. Do that for each frame before pd.concat, and add ignore_index=True to the concat. Then pivot on Type and Source should work, because each Type and Source pair appears only once. If it still complains, run result.duplicated(['Type','Source']).sum() to see which rows repeat.

1

u/Baner-Fournadet 4h ago

yeah splitting by position with iloc is the cleanest way around those duplicate column names

1

u/woooee 8h 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.

1

u/Dragoran21 5h ago

So and so. I have passed a university level course on Python, but I don't use it every day, so I keep forgetting specifics. Yes, yes, and no. Background is: "Ugh, I want to make a nice table of the distribution of genes in sample subgroups so my analysis would be simpler, but there are almost a hundred genes, so doing this manually would be a pain in the ass".

1

u/woooee 3h ago

I assume you are reading a text file which is easy. Then you split() each record (don't know what character as you didn't show any actual data). In your example data posted above, you would split on white space. Will try to post an example program using the data from your post later today.

1

u/Dragoran21 3h ago

I have, look the post.

1

u/woooee 1h ago

You did not say what "I ran into an issue" was, so I assume that it is not getting the full line as in your original output example. IMHO Pandas is an unnecessary layer/complication for something this straight forward, but you of course have to decide that for yourself.

'''
Into something looking like this one:
Type    Alpha   Beta    Gamma
A       100     80      90
B       20      20      30
C       1       1       0
X       1       nan     nan
Y       nan     2       nan
Z       nan     nan     1
'''

input_data = '''Type    Alpha   Type    Beta    Type    Gamma
A       100     A       80      A       90
B       20      B       40      B       30
C       1       C       1       C       0
X       1       Y       2       Z       1'''

## simulate a file read
file_input = input_data.split("\n")
file_output = open("./test.txt", mode="w")
## and strip off first record / titles
for rec in file_input[1:]:
    rec_list = rec.split()
    if rec_list[0] < "X":
        file_output.write(
        f"{rec_list[0]:3s}  {rec_list[1]:5s}  {rec_list[3]:5s}  {rec_list[5]}\n")
    else:  ## assume there is always all three, X, Y, Z
        if rec_list[0] == "X":
            ## could also be done with a loop
            file_output.write(f"{rec_list[0]:3s}  {rec_list[1]:5s}  nan  nan\n")
            file_output.write(f"{rec_list[2]:3s}  nan    {rec_list[3]:5s}nan\n")
            file_output.write(f"{rec_list[4]:3s}  nan    nan  {rec_list[5]:5s}\n")

file_output.close()

1

u/Dragoran21 1h ago

The issue is when I tried to pivot the dataframe:

"ValueError: Index contains duplicate entries, cannot reshape".

I managed to get the table into this form following Likh-98's advice:

Type Value Source

0 A 100 Alpha

1 B 20

2 C 1

3 X 1

0 A 80 Beta

1 B 40

2 C 1

3 Y 2

0 A 90 Gamma

1 B 30

2 C 0

3 Z 1

I don't think that code will help with the actual data I want to turn into a table. It contains 89 unique genes.

1

u/Educational_Virus672 7h ago

please be welcoming to new comers. in forums like r/learnpython we are here to "learn" for a reason

1

u/Hour_Bookkeeper129 6h ago

What learning? No code posted so nothing to learn from. This is LearnPython not TryToRipOffAProgrammer

1

u/Dragoran21 4h ago

Oh I am sorry, I didn't know only lecturers could make post.

2

u/woooee 6h ago

My question is a serious one. A previous post recommended Pandas. If the OP does not already know Pandas then read-the-file-and-process-each-record would be the easiest solution. A good answer requires a good, detailed question, which it was not. Note that holier than thou comments will not be received well by me. If you want to support this sub-reddit then support those of us who have volunteered (for years) as well.

1

u/seanv507 9h 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

0

u/Educational_Virus672 7h ago

it is not appropriate to recommend ai in most learn programming forums like r/learnpython since recommending ai here breaks the idea of "learn" entirely unless you tell them to use it as a form of search engine or a direct tutor