Home > Enterprise >  Transpose by using a dictionary
Transpose by using a dictionary

Time:12-24

Input:

A   a
B   b
C   c
D   d
E   e

Expected output:

A   B   C   D   E
a   b   c   d   e

Code:

dic = {}
with open(input_file, 'r') as input:
    for line in input:
        block = line.strip().split('\t')[0]
        dic[block] = line.strip().split('\t')[1]


with open(output_file, 'w') as ouput:
    for key, value in dic.items():

I want to change 'input' to 'expected output' without using pandas' transpose function. I added each string in a dictionary. So, how can I extract the 'expected output' using the dictionary?

CodePudding user response:

Use zip:

TEST = [
    ['A', 'a'],
    ['B', 'b'],
    ['C', 'c'],
    ['D', 'd'],
    ['E', 'e'],
]

result = list(zip(*TEST))

The result is (pretty formatted):

[
    ('A', 'B', 'C', 'D', 'E'),
    ('a', 'b', 'c', 'd', 'e'),
]

CodePudding user response:

I still don't completely understand what you're trying to do but let's try this.

With the first loop, you created dic from Input, right?

dic = {'A':'a','B':'b','C':'c','D':'d','E':'e'}

If you pass dic to pd.DataFrame with index=[0], as

df = pd.DataFrame(dic, index=[0])

you can get a DataFrame below:

   A  B  C  D  E
0  a  b  c  d  e

If you want a list however, you can separate dic by keys and values as:

lsts = [list(dic.keys()), list(dic.values())]

which will give you:

[['A', 'B', 'C', 'D', 'E'], ['a', 'b', 'c', 'd', 'e']]
  • Related