简体   繁体   中英

How to convert an unlabled key value pair dictionary data into 2 columns in Python

I have an array as input in key value pair:

test = {'a':32, 'b':21, 'c':92}

I have to get the result in a new data frame as follows:

col1 col2
a 32
b 21
c 92

Try:

test = {"a": 32, "b": 21, "c": 92}

df = pd.DataFrame({"col1": test.keys(), "col2": test.values()})
print(df)

Prints:

  col1  col2
0    a    32
1    b    21
2    c    92

Using unpacking:

df = pd.DataFrame([*test.items()], columns=['col1', 'col2'])

Using a Series:

df = pd.Series(test, name='col2').rename_axis('col1').reset_index()

output:

  col1  col2
0    a    32
1    b    21
2    c    92

There's maybe shorter / better ways of doing this but here goes


test = {'a':32, 'b':21, 'c':92}

df = pd.DataFrame(test, index=[0])
df = df.stack().reset_index(-1).iloc[:, ::-1]
df.columns = ['col2', 'col1']
df.reset_index()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM