pandas 如何将字典转换为3列 Dataframe ?

mwg9r5ms  于 2023-05-21  发布在  其他
关注(0)|答案(2)|浏览(192)

我正在把一个dict转换成一个 Dataframe 。我的字典就像key:[value]
Dict示例;
{'StringAwesome': PureWindowsPath('//server/cool.log'), 'StringCool': PureWindowsPath('//server/rad.log')}
我要三排像;
0 -- key -- value
我用的是orient=index。虽然很接近,但它给了我;

0
key -- value

最后我想用

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()

我该如何实现?谢谢

smtd7mpg

smtd7mpg1#

IIUC,您可以用途:

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

或者:

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

输出:

columnA columnB
0    keyA  valueA
1    keyB  valueB
ryhaxcpt

ryhaxcpt2#

这个有用吗

import pandas as pd 

my_dict = {"key1": "val_1", "key2": "val_2"}
processed_dict = [(k,v) for k,v in my_dict.items() ] 

df = pd.DataFrame.from_records( processed_dict, columns=['col_1', 'col_2'] )
print(df)

输出:

col_1  col_2
0  key1  val_1
1  key2  val_2

相关问题