Home > Software design >  How to convert an unlabled key value pair dictionary data into 2 columns in Python
How to convert an unlabled key value pair dictionary data into 2 columns in Python

Time:08-24

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related