简体   繁体   中英

Create a dataframe from a dictionary with multiple keys and values

So I have a dictionary with 20 keys, all structured like so (same length):

{'head':              X         Y         Z
 0    -0.203363  1.554352  1.102800
 1    -0.203410  1.554336  1.103019
 2    -0.203449  1.554318  1.103236
 3    -0.203475  1.554299  1.103446
 4    -0.203484  1.554278  1.103648
 ...        ...       ...       ...
 7441 -0.223008  1.542740  0.598634
 7442 -0.222734  1.542608  0.599076
 7443 -0.222466  1.542475  0.599520
 7444 -0.222207  1.542346  0.599956
 7445 -0.221962  1.542225  0.600375

I'm trying to convert this dictionary to a dataframe, but I'm having trouble with getting the output I want. What I want is a dataframe structured like so: columns = [headX, headY, headZ etc.] and rows being the 0-7445 rows .

Is that possible? I've tried:

df = pd.DataFrame.from_dict(mydict, orient="columns")

And different variations of that, but can't get the desired output.

Any help will be great!

EDIT: The output I want has 60 columns in total, ie from each of the 20 keys, I want an X, Y, Z for each of them. So columns would be: [key1X, key1Y, key1Z, key2X, key2Y, key2Z, ...] . So the dataframe will be 60 columns x 7446 rows .

Use concat with axis=1 and then flatten Multiindex by f-string s:

df = pd.concat(d, axis=1)
df.columns = df.columns.map(lambda x: f'{x[0]}_{x[1]}')

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