I am having a csv
file, have its data in dataframe
:
df = pd.read_csv(r'C:\Users\isha\Desktop\SF head count report 7 mar 2019.csv')
The data frame have more than 20 columns, but I need to create a dictionary by using only 2 columns from dataframe
.
This is the purpose of the usecols
parameter in read_csv
df = pd.read_csv('my_file.csv', usecols=['first_col','second_col'])
You can give it the indices or names of the columns you want and Pandas will store only these in your df.
To create a dictionary, you can call the df's builtin method df.to_dict()
By default the key will be your index, and the two columns the values. If you just want these 2 columns, one as key and one as value, then follow Chris A's advice:
df.set_index('your_key_column')['your_value_column'].to_dict()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.