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
EDIT2: Here are a few ways to do it.
One:
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:]
df2.rename(columns={'Type.1': 'Type'}, inplace=True)
df3.rename(columns={'Type.2': 'Type'}, inplace=True)
x=pd.concat([d.set_index('Type') for d in [df1, df2, df3]], axis=1)
print(x)
Two:
df = pd.read_csv('Table of Test.txt', sep='\t')
type_cols = df.columns.str.startswith('Type')
# Check type column names correctly positioned
assert all(value is not bool(i % 2) for i, value in enumerate(type_cols))
frames = [
df.iloc[:, [i, i+1]].set_index(df.columns[i])
for i in np.flatnonzero(type_cols)
]
df_new = pd.concat(frames, axis=1)
print(df_new)
There, solved!
PS: Is it just me, or are you also getting double text when you post to a code block?