ADVERTISEMENT
ADVERTISEMENT

How to create a dictionary of two Pandas DataFrames columns?

Given two Pandas DataFrames, we have to create a dictionary.
Submitted by Pranit Sharma, on June 07, 2022

Columns are the different fields that contain their particular values when we create a DataFrame. We can perform certain operations on both rows & column values.

To create a dictionary of two pandas DataFrame columns - we will use zip() method, it will combine the values of both columns then we will convert the result into a dictionary.

To apply this method to specific columns, we need to define the specific columns at time of function calling.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

# Importing pandas package
import pandas as pd

# Creating a DataFrame
df = pd.DataFrame({
    'Cities':['Indore','Bhopal','Gwalior','Indore'],
    'Code':[731,755,751,731]
})

# Display DataFrames
print("DataFrames:\n",df,"\n")

# Using Zip method
ans = zip(df.Cities,df.Code)

# Converting it into list
ans = list(ans)

# Converting it into dictionary
ans = dict(ans)

# Display ans
print("Result of apply:\n",ans,"\n")

Output:

Example: create a dictionary of two DataFrames

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.