Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - Create dataframe with only one row from dictionary containing lists

I have this dictionary:

d = {'val_1': [1,2,3,4,5], 'val_2': 4}

And I want to create a pandas DataFrame from this with only one row.

When I do:

import pandas as pd
df = pd.DataFrame(d)
print(df)

I get 5 rows:

    val_1   val_2
0   1       4
1   2       4
2   3       4
3   4       4
4   5       4

However, when I append it to the existing dataframe, I get the behavior I want.

import pandas as pd
df = pd.DataFrame(d)
df = df.append(d, ignore_index=True)
print(df)

    val_1           val_2
0   1               4
1   2               4
2   3               4
3   4               4
4   5               4
5   [1, 2, 3, 4, 5] 4

How can I create the dataframe from the dict, and get only one row as in the append case?

    val_1             val_2
0   [1, 2, 3, 4, 5]   4
like image 588
heisen Avatar asked May 05 '18 21:05

heisen


People also ask

Can we create DataFrame from dictionary of lists?

It is the most commonly used pandas object. Creating pandas data-frame from lists using dictionary can be achieved in multiple ways. Let's discuss different ways to create a DataFrame one by one. With this method in Pandas, we can transform a dictionary of lists into a dataframe.

How will you create a DataFrame from dictionary with key values as rows?

Method 1: Create DataFrame from Dictionary using default Constructor of pandas. Dataframe class. Method 2: Create DataFrame from Dictionary with user-defined indexes. Method 3: Create DataFrame from simple dictionary i.e dictionary with key and simple value like integer or string value.

Can we create DataFrame using only one series also?

Series can only contain single list with index, whereas dataframe can be made of more than one series or we can say that a dataframe is a collection of series that can be used to analyse the data.

What method creates a pandas DataFrame from a dictionary?

Create dataframe with Pandas from_dict() Method If that sounds repetitious, since the regular constructor works with dictionaries, you can see from the example below that the from_dict() method supports parameters unique to dictionaries. In the code, the keys of the dictionary are columns. The row indexes are numbers.


2 Answers

Wrap the values in a list:

pd.DataFrame({k: [v] for k, v in d.items()})
#             val_1   val_2
#0  [1, 2, 3, 4, 5]       4
like image 110
Psidom Avatar answered Oct 26 '22 00:10

Psidom


You can start with pd.Series instead:

pd.Series(d).to_frame().T

             val_1 val_2
0  [1, 2, 3, 4, 5]     4
like image 22
cs95 Avatar answered Oct 25 '22 22:10

cs95