2

In the following code, I have defined a dictionary and then converted it to a dataframe

my_dict = {
'A' : [1,2],
'B' : [4,5,6]
}
df = pd.DataFrame()
df = df.append(my_dict, ignore_index=True)

The output is a [1 rows x 2 columns] dataframe which looks like

         A         B
0    [1,2]   [4,5,6]

However, I would like to reshape it as

     A     B
0    1     4
1    2     5
2          6

How can I fix the code for that purpose?

mahmood
  • 23,197
  • 49
  • 147
  • 242
  • 5
    Maybe this is what you're looking for? https://stackoverflow.com/questions/19736080/creating-dataframe-from-a-dictionary-where-entries-have-different-lengths – Iguananaut May 13 '22 at 12:56
  • Does this answer your question? [Creating dataframe from a dictionary where entries have different lengths](https://stackoverflow.com/questions/19736080/creating-dataframe-from-a-dictionary-where-entries-have-different-lengths) – BeRT2me May 13 '22 at 21:31

4 Answers4

2

You might use pandas.Series.explode as follows

import pandas as pd
my_dict = {
'A' : [1,2],
'B' : [4,5,6]
}
df = pd.DataFrame()
df = df.append(my_dict, ignore_index=True)
df = df.apply(lambda x:x.explode(ignore_index=True))
print(df)

output

     A  B
0    1  4
1    2  5
2  NaN  6

I apply explode to each column with ignore_index=True which prevent duplicate indices.

Daweo
  • 31,313
  • 3
  • 12
  • 25
1

This will give you the results you are looking for if you don't mind changing your code a little

my_dict = {
'A' : [1,2,''],
'B' : [4,5,6]
}
df = pd.DataFrame(my_dict)
df
ArchAngelPwn
  • 2,891
  • 1
  • 4
  • 17
  • That `''` to make the vectors the same size is a bit tricky. For this example it is fine, but my code has more than two elements and vector lengths are very variable. – mahmood May 13 '22 at 13:00
  • But this can fix the variable lengths https://stackoverflow.com/a/63821093/859227 – mahmood May 13 '22 at 13:01
  • would replacing the '' with a np.nan or None work for what you need? – ArchAngelPwn May 13 '22 at 13:02
  • Yes but as I said, that needs manual modifications to the vectors to make them the same size. – mahmood May 13 '22 at 13:15
1

Another way of doing this is:

df = pd.DataFrame.from_dict(my_dict, 'index').T
print(df)

Output:

     A    B
0  1.0  4.0
1  2.0  5.0
2  NaN  6.0
BeRT2me
  • 12,699
  • 2
  • 13
  • 31
0

Try this instead. you need to assign the dictionary to the dataframe. I've run it. It should give you the output you desire. don't use the append. It's to append one dataframe to another

import pandas as pd 

my_dict = {
'A' : [1,2,''],
'B' : [4,5,6]
}
df = pd.DataFrame(data=my_dict)
#df = df.append(my_dict, ignore_index=True)

print(df)
Janet
  • 75
  • 5