1
$\begingroup$

I am trying to put a dataframe into dictionary ,with the first column as the key ,the numbers in a row would be the value . how should I do it ? I tried to_dict but did not work , my df has no header or rownumber.

enter image description here

$\endgroup$
0
$\begingroup$

Works for me with numbers as headers:

import pandas as pd
df = pd.DataFrame({'1': [1, 2],
                 '2': [0.5, 0.75]},
                 index=['row1', 'row2'])
df.to_dict()

Output:

{'1': {'row1': 1, 'row2': 2}, '2': {'row1': 0.5, 'row2': 0.75}}

You may also specify column names when you read the data:

Cov = pd.read_csv("path/to/file.txt", 
                  sep='\t', 
                  names=["Sequence", "Start", "End", "Coverage"])

See: https://stackoverflow.com/questions/34091877/how-to-add-header-row-to-a-pandas-dataframe

$\endgroup$
0
$\begingroup$

One solution is to use dictionary comprehension (IIUC).

import pandas as pd

df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]})
print (df)

    a  b  c
0  1  4  7
1  2  5  8
2  3  6  9

d = {k:v for k, v in df.apply(lambda r: {r[0],",".join(r[1:].astype('str'))}, axis=1)}
print(d)

{1: '4,7', 2: '5,8', 3: '6,9'}

$\endgroup$
0
$\begingroup$

If I understand the problem correctly, the first column should be the keys while the numbers that follow are the values. Then, the values should be lists right?

Try this code.

import pandas as pd

df = pd.DataFrame(
    [
        ['C', 5, 4, 3, 2, 1],
        ['c', 6, 7, 8, 9, 10],
        ['(', 11, 12, 13, 14, 15],
        [')', 16, 17, 18, 19, 20],
        ['O', 21, 22, 23, 24, 25]
    ]
)

print(df)
print('\n')

print({df.iloc[i][0]: df.iloc[i][1:].tolist() for i in df.T})

Here's the output:

   0   1   2   3   4   5
0  C   5   4   3   2   1
1  c   6   7   8   9  10
2  (  11  12  13  14  15
3  )  16  17  18  19  20
4  O  21  22  23  24  25


{'C': [5, 4, 3, 2, 1], 'c': [6, 7, 8, 9, 10], '(': [11, 12, 13, 14, 15], ')': [16, 17, 18, 19, 20], 'O': [21, 22, 23, 24, 25]}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.