Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Panda, Update column values based on a list of ID and new Values

I have a df with and ID and Sell columns. I want to update the Sell column, using a list of new Sells (not all raws need to be updated - just some of them). In all examples I have seen, the value is always the same or is coming from a column. In my case, I have a dynamic value.

This is what I would like:

file = ('something.csv') # Has 300 rows
IDList= [['453164259','453106168','453163869','453164463'] # [ID] 
SellList=[120,270,350,410] # Sells values
csv = path_pattern = os.path.join(os.getcwd(), file)
df = pd.read_csv(file)
df.loc[df['Id'].isin(IDList[x]), 'Sell'] = SellList[x] # Update the rows with the corresponding Sell value of the ID.
df.to_csv(file)

Any ideas? Thanks in advance

like image 524
crianopa Avatar asked Sep 05 '25 13:09

crianopa


2 Answers

Assuming 'id' is a string (as mentioned in IDList) & is not index of your df

IDList= [['453164259','453106168','453163869','453164463'] # [ID] 
SellList=[120,270,350,410]
id_dict={x:y for x,y in zip(IDList,SellList)}
for index,row in df.iterrows():
    if row['id'] in IDList:
         df.loc[str(index),'Sell']=id_dict[row['id']]

If id is index:

IDList= [['453164259','453106168','453163869','453164463'] # [ID] 
SellList=[120,270,350,410]
id_dict={x:y for x,y in zip(IDList,SellList)}
for index,row in df.iterrows():
    if index in IDList:
         df.loc[str(index),'Sell']=id_dict[index]

What I did is created a dictionary using IDlist & SellList & than looped over the df using iterrows()

like image 153
Mehul Gupta Avatar answered Sep 08 '25 20:09

Mehul Gupta


df = pd.read_csv('something.csv')
IDList= ['453164259','453106168','453163869','453164463']
SellList=[120,270,350,410]

This will work efficiently, specially for large files:

df.set_index('id', inplace=True)
df.loc[IDList, 'Sell'] = SellList
df.reset_index() ## not mandatory, just in case you need 'id' back as a column
df.to_csv(file)
like image 41
amalik2205 Avatar answered Sep 08 '25 20:09

amalik2205