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
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.
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.
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.
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.
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
You can start with pd.Series
instead:
pd.Series(d).to_frame().T
val_1 val_2
0 [1, 2, 3, 4, 5] 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With