Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I turn a dictionary into a 3 column dataframe?

I am turning a dict into a dataframe. My dict is like key:[value].

Dict example;

{'StringAwesome': PureWindowsPath('//server/cool.log'), 'StringCool': PureWindowsPath('//server/rad.log')}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want three rows like;

0 -- key -- value

I used orient=index. Which is close, but it gives me;

       0
key -- value

I’d like to end up with;

index -- columnA -- columnB
0     -- key     -- value
def build_failmacro_df() -> pd.DataFrame:
    """build a dataframe containing sites with failing macros"""
    sites = get_failing_sites()
    df = pd.DataFrame.from_dict(sites, orient='index')
    df.to_csv(Path(r'C:\test.csv')) 
    #return df

build_failmacro_df()

How can I achieve? Thanks.

>Solution :

IIUC, you can use:

sites = {'keyA': ['valueA'], 'keyB': ['valueB']}
df = (pd.DataFrame.from_dict(sites, orient='index')[0]
        .rename_axis('columnA').reset_index(name='columnB')
     )

Or:

sites = {'keyA': 'valueA', 'keyB': 'valueB'}
df = (pd.Series(sites)
        .rename_axis('columnA').reset_index(name='columnB')
     )

Output:

  columnA columnB
0    keyA  valueA
1    keyB  valueB
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading