r/learnpython • u/Dragoran21 • 9h ago
Looking a way to combine columns based on values.
I wish to alter a table/dataframe like this one:
| 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 |
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 |
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
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
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
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.