search
Search
Unlock 100+ guides
search toc
close
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to

# Initialising a DataFrame using a dictionary in Pandas

schedule Aug 12, 2023
Last updated
local_offer
PythonPandas
Tags
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

# Using a dictionary of arrays

To create a DataFrame using a dictionary of arrays:

``` df = pd.DataFrame({"A":[3,4], "B":[5,6]})df A B0 3 51 4 6 ```

Here, the key-value pair of the dictionary is as follows:

• `key`: column label

• `value`: values of that column

Also, since the `data` does not contain any index (row labels), the default integer indices (`[0,1]`) are used.

# Using a nested dictionary

To create a DataFrame using a nested dictionary:

``` col_one = {"a":3, "b":4}col_two = {"a":5, "b":6}df = pd.DataFrame({"A":col_one, "B":col_two})df A Ba 3 5b 4 6 ```

Here, we've specified the index in `col_one` and `col_two`.

# Using a dictionary whose key-value pair represents a row

Consider the following dictionary that holds some data:

``` data = { "alex": 20, "bob": 30, "cathy": 40} ```

We want to create a DataFrame whose values are all the key-value pairs of `data`. Pandas does not provide a direct solution for this, so we ourselves must extract the keys and values of `data` as lists:

``` arr_name = list(data.keys())arr_age = list(data.values()) ```

We can then use the first approach of initialising a DataFrame using a dictionary of arrays:

``` df = pd.DataFrame({"name":arr_name, "age":arr_age})df name age0 alex 201 bob 302 cathy 40 ```
Edited by 0 others
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!