简体   繁体   中英

How to create a dataframe from a python dictionary of lists?

import pandas as pd

new_dict = {'mid': ['1', '2'], 'type': ['a', 'b']}

df = pd.DataFrame(new_dict.items(), columns=list(new_dict), index=None)

print(df)

This print out as:

mid    type
0   mid  [1, 2]
1  type  [a, b]

But I hope it prints out as:

mid    type
1       a
2       b

Is that possible?

--Edit : As @DeepSpace pointed out in the comments to my answer, your mistake was in passing the new_dict.items() function result as the data rather than just the dict itself.

Keeping it simple, if you just do this, without needing to specify the columns and index arguments, it works:

new_dict = {"mid":["1","2"], "type":["a", "b"]}
df = pd.DataFrame(new_dict)
print(df)

This is the result, which I think is what you want:

  mid type
0   1    a
1   2    b

And here it is with specifying something for columns and index: new_dict = {"mid":["1","2"], "type":["a", "b"]} df = pd.DataFrame(new_dict, columns=list(new_dict), index=None) print(df)

output:

  mid type
0   1    a
1   2    b

And, if you were trying to print the Dataframe without showing the index, which seems to be your desired output, you can do this:

print(df.to_string(index=False))

mid type
  1    a
  2    b

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