How to use pandas to extract two values from csv at the same time? (two columns, same row)
Clash Royale CLAN TAG#URR8PPP
How to use pandas to extract two values from csv at the same time? (two columns, same row)
I am using pandas
to read a csv file into my python code. I understand I can grab a specific value from a specific column for all rows and append it to an array as follows:
pandas
import pandas as pd
df = pd.read_csv('File.txt')
for row in df[df.columns[0]]:
playerNames.append(row)
However, I want to, instead, grab the values from columns 0 and 2 at the same time to populate a dictionary. In my head it would be something like:
for row in df[df.columns[0,2]]:
playerNameDictionary[row.columns[0]] = row.columns[2]
Obviously this wrong (don't even think it compiles) but I am just at a loss as to how I would go about doing this.
3 Answers
3
Loops are anti-pattern for Pandas. More efficiently, you can use pd.Series.to_dict
:
pd.Series.to_dict
key_col, val_col = df.columns[[0, 2]]
playerNameDictionary = df.set_index(key_col)[val_col].to_dict()
@AlekPiasecki, Correct.
– jpp
Aug 11 at 8:43
dict_sample = dict(zip(df.column1, df.column2))
column1 & column 2 stands for the column names. It will create a key value pair with key being column1 data and value being column2 data. I hope I understood the question right.
Make sure your future keys are not duplicate.
For Python <3
my_dict =
for key, value in zip(df.column0, df.column2)):
my_dict [key] = value
For Python 3>
my_dict = dict(zip(df.column0, df.column2))
and this will do it for every row? No need to loop through it?
– Alek Piasecki
Aug 10 at 21:16
Yes do give a try
– mad_
Aug 10 at 23:33
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
and this will do it for every row? No need to loop through it?
– Alek Piasecki
Aug 10 at 21:15