www.pythonforbeginners.com
Open in
urlscan Pro
2a06:98c1:3120::3
Public Scan
URL:
https://www.pythonforbeginners.com/basics/append-dictionary-to-dataframe-in-python
Submission: On February 14 via manual from PL — Scanned from NL
Submission: On February 14 via manual from PL — Scanned from NL
Form analysis
3 forms found in the DOMGET https://www.pythonforbeginners.com/
<form class="search-form" method="get" action="https://www.pythonforbeginners.com/" role="search"><label class="search-form-label screen-reader-text" for="searchform-1">Search this website</label><input class="search-form-input" type="search"
name="s" id="searchform-1" placeholder="Search this website"><input class="search-form-submit" type="submit" value="Search">
<meta content="https://www.pythonforbeginners.com/?s={s}">
</form>
POST
<form id="free-guide-to-learning-python-1" class="yikes-easy-mc-form yikes-easy-mc-form-1 sidebar_email_form" method="POST" data-attr-form-id="1"> <label for="yikes-easy-mc-form-1-EMAIL" class="EMAIL-label yikes-mailchimp-field-required "> <span
class="EMAIL-label"> Email Address </span> <input id="yikes-easy-mc-form-1-EMAIL" name="EMAIL" placeholder="" class="yikes-easy-mc-email " required="required" type="email" value=""> </label> <label for="yikes-easy-mc-form-1-SOURCE"
style="display:none;" class="SOURCE-label "> <span class="SOURCE-label"> source </span> <input id="yikes-easy-mc-form-1-SOURCE" name="SOURCE" placeholder="" class="yikes-easy-mc-text " type="text" value="Sidebar"> </label> <input type="hidden"
name="yikes-mailchimp-honeypot" id="yikes-mailchimp-honeypot-1" value=""> <input type="hidden" name="yikes-mailchimp-associated-list-id" id="yikes-mailchimp-associated-list-id-1" value="544dbfab57"> <input type="hidden"
name="yikes-mailchimp-submitted-form" id="yikes-mailchimp-submitted-form-1" value="1"> <button type="submit" class="yikes-easy-mc-submit-button yikes-easy-mc-submit-button-1 btn btn-primary sidebar_email_form_button"> <span
class="yikes-mailchimp-submit-button-span-text">Subscribe</span></button> <input type="hidden" id="yikes_easy_mc_new_subscriber_1" name="yikes_easy_mc_new_subscriber" value="970c8844ae"> <input type="hidden" name="_wp_http_referer"
value="/basics/append-dictionary-to-dataframe-in-python"></form>
<form class="g-jdoua8 g-hxd0xw" novalidate="novalidate">
<div class="gw5f1np"><w-div class="g-p0ly7s g65zlmy"><label for="gscw_email_input" class="g-6l6pad">Email</label><w-div class="g-kmcsz7 g-qyrply"><input type="email" maxlength="1000" title="Email" placeholder="Email address" name="email"
id="gscw_email_input" class="g-xhids6 g-b4ef17"></w-div></w-div> <button type="submit" class="g3ylmud "> <span class="gyzp9jm">Subscribe</span> <span class="g-recys7" title="Subscribe"></span></button></div>
</form>
Text Content
* Skip to primary navigation * Skip to main content * Skip to primary sidebar PythonForBeginners.com Learn By Example * Home * Learn Python * Python Tutorial * Categories * Basics * Lists * Dictionary * Code Snippets * Comments * Modules * API * Beautiful Soup * Cheatsheet * Games * Loops * Python Courses * Python 3 For Beginners You are here: Home / Basics / Append Dictionary to Dataframe in Python APPEND DICTIONARY TO DATAFRAME IN PYTHON Author: Aditya Raj Last Updated: November 9, 2022 We use a python dictionary to store key-value pairs. Similarly, Dataframes are used to store records containing values associated with a key in the tabular format. In this article, we will discuss how we can append a dictionary to a dataframe in Python. HOW TO APPEND A DICTIONARY TO A DATAFRAME IN PYTHON? To append a dictionary to a pandas dataframe, we will use the append() method. The append() method, when invoked on a dataframe, takes a dictionary as its input argument and returns a new dataframe. The append() method also takes the value True as an input argument for its ignore_index parameter. LATEST VIDEOS Tech and Gaming 0 seconds of 34 secondsVolume 0% Press shift question mark to access a list of keyboard shortcuts Keyboard ShortcutsEnabledDisabled Play/PauseSPACE Increase Volume↑ Decrease Volume↓ Seek Forward→ Seek Backward← Captions On/Offc Fullscreen/Exit Fullscreenf Mute/Unmutem Seek %0-9 Live 00:25 00:09 00:34 The output dataframe contains the dictionary values appended as a row in the original dataframe. You can observe this in the following example. import pandas as pd names=pd.read_csv("name.csv") print("The input dataframe is:") print(names) myDict={"Class":3, "Roll":22, "Name":"Sakshi"} print("The dictionary is:") print(myDict) names=names.append(myDict,ignore_index=True) print("The output dataframe is:") print(names) Output The input dataframe is: Class Roll Name 0 1 11 Aditya 1 1 12 Chris 2 1 13 Sam 3 2 1 Joel 4 2 22 Tom 5 2 44 Samantha 6 3 33 Tina 7 3 34 Amy The dictionary is: {'Class': 3, 'Roll': 22, 'Name': 'Sakshi'} The output dataframe is: Class Roll Name 0 1 11 Aditya 1 1 12 Chris 2 1 13 Sam 3 2 1 Joel 4 2 22 Tom 5 2 44 Samantha 6 3 33 Tina 7 3 34 Amy 8 3 22 Sakshi If a dictionary has less number of keys than the columns specified in the dataframe, the remaining columns are assigned the value NaN in the rows where the dictionary is appended. You can observe this in the following example. import pandas as pd names=pd.read_csv("name.csv") print("The input dataframe is:") print(names) myDict={"Class":3, "Name":"Sakshi"} print("The dictionary is:") print(myDict) names=names.append(myDict,ignore_index=True) print("The output dataframe is:") print(names) Output: The input dataframe is: Class Roll Name 0 1 11 Aditya 1 1 12 Chris 2 1 13 Sam 3 2 1 Joel 4 2 22 Tom 5 2 44 Samantha 6 3 33 Tina 7 3 34 Amy The dictionary is: {'Class': 3, 'Name': 'Sakshi'} The output dataframe is: Class Roll Name 0 1 11.0 Aditya 1 1 12.0 Chris 2 1 13.0 Sam 3 2 1.0 Joel 4 2 22.0 Tom 5 2 44.0 Samantha 6 3 33.0 Tina 7 3 34.0 Amy 8 3 NaN Sakshi If a dictionary doesn’t have the keys same as the columns in the dataframe, a new column is added to the dataframe for each key that is not present in the dataframe as the column name. While appending a dictionary with key values different from the column names, the values for the new columns in the existing rows are filled as NaN. Similarly, the columns which are not present in the dictionary but are present in the dataframe are assigned the value NaN is the row where the dictionary is appended. You can observe that in the following example. import pandas as pd names=pd.read_csv("name.csv") print("The input dataframe is:") print(names) myDict={"Class":3, "Roll":22, "Name":"Sakshi","Height":160} print("The dictionary is:") print(myDict) names=names.append(myDict,ignore_index=True) print("The output dataframe is:") print(names) Output: The input dataframe is: Class Roll Name 0 1 11 Aditya 1 1 12 Chris 2 1 13 Sam 3 2 1 Joel 4 2 22 Tom 5 2 44 Samantha 6 3 33 Tina 7 3 34 Amy The dictionary is: {'Class': 3, 'Roll': 22, 'Name': 'Sakshi', 'Height': 160} The output dataframe is: Class Roll Name Height 0 1 11 Aditya NaN 1 1 12 Chris NaN 2 1 13 Sam NaN 3 2 1 Joel NaN 4 2 22 Tom NaN 5 2 44 Samantha NaN 6 3 33 Tina NaN 7 3 34 Amy NaN 8 3 22 Sakshi 160.0 To append two or more dictionaries or a list of dictionaries to the dataframe, you can use a for loop along with the append() method. In the for loop, you can append each dictionary to the dataframe. Suggested Reading: If you are into machine learning, you can read this article on k-prototypes clustering with numerical example. You might also like this article on data ink ratio. The append() method will be deprecated in near future. So, you can use the pandas concat() method to append a dictionary to the dataframe as shown below. import pandas as pd names=pd.read_csv("name.csv") print("The input dataframe is:") print(names) myDict={"Class":3, "Roll":22, "Name":"Sakshi","Height":160} print("The dictionary is:") print(myDict) tempDf=pd.DataFrame([myDict]) names=pd.concat([names,tempDf],ignore_index=True) print("The output dataframe is:") print(names) Output: The input dataframe is: Class Roll Name 0 1 11 Aditya 1 1 12 Chris 2 1 13 Sam 3 2 1 Joel 4 2 22 Tom 5 2 44 Samantha 6 3 33 Tina 7 3 34 Amy The dictionary is: {'Class': 3, 'Roll': 22, 'Name': 'Sakshi', 'Height': 160} The output dataframe is: Class Roll Name Height 0 1 11 Aditya NaN 1 1 12 Chris NaN 2 1 13 Sam NaN 3 2 1 Joel NaN 4 2 22 Tom NaN 5 2 44 Samantha NaN 6 3 33 Tina NaN 7 3 34 Amy NaN 8 3 22 Sakshi 160.0 CONCLUSION In this article, we have discussed how to append a dictionary to a dataframe in python. To know more about python programming, you can read this article on dictionary comprehension in python. You might also like this article on list comprehension in python. RELATED Append a New Row in a Dataframe in PythonMarch 11, 2022In "Basics" List of Dictionaries to Dataframe in PythonJune 24, 2022In "Basics" Pandas Replace Values in Dataframe or SeriesJanuary 9, 2023In "Basics" Advertisement RECOMMENDED PYTHON TRAINING Course: Python 3 For Beginners Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics. Enroll Now Filed Under: Basics Author: Aditya Raj MORE PYTHON TOPICS API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2 PRIMARY SIDEBAR Search this website MENU * Basics * Cheatsheet * Code Snippets * Development * Dictionary * Error Handling * Lists * Loops * Modules * Scripts * Strings * System & OS * Web GET OUR FREE GUIDE TO LEARNING PYTHON Email Address source Subscribe MOST POPULAR CONTENT * Reading and Writing Files in Python * Python Dictionary – How To Create Dictionaries In Python * How to use Split in Python * Python String Concatenation and Formatting * List Comprehensions in Python * How to Use sys.argv in Python? * How to use comments in Python * Try and Except in Python RECENT POSTS * Convert XML to Dictionary in Python * Convert Python Dictionary to YAML * Convert YAML to JSON in Python * Load JSON into a Python Dictionary * Convert JSON to YAML in Python Copyright © 2012–2023 · PythonForBeginners.com * Home * Contact Us * Privacy Policy * Write For Us Update Privacy Preferences An Elite CafeMedia Tech Publisher Thank you! You have successfully subscribed. Download our Free Guide To Learning Python Subscribe to receive our Free Guide To Learning Python! Email Subscribe We will not share your information with anyone Learn Python Start to Finish Didn't find what you were looking for? Sorry about that, but we have put together a comprehensive Python course with everything you need. This course is perfect for beginners and intermediate Python programmers. Give it try! Only $9.95