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

Advertisements

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')}

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

Leave a ReplyCancel reply