使用Pandas,根据ID和新值列表更新列值

2024-10-05 14:21:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个df和ID和Sell列。我想使用一个新销售列表来更新“销售”列(不是所有的RAW都需要更新,只是其中的一部分)。在我看到的所有示例中,值总是相同的,或者来自一列。在我的例子中,我有一个动态值

这就是我想要的:

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)

有什么想法吗? 提前谢谢


Tags: csvthepathid示例df列表raw
2条回答
df = pd.read_csv('something.csv')
IDList= ['453164259','453106168','453163869','453164463']
SellList=[120,270,350,410]

这将有效地工作,特别是对于大型文件:

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)

假设'id'是字符串(如IDList中所述)&;不是您的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']]

如果id是索引:

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]

我所做的是使用IDlist&;销售名单及;然后使用iterrows()在df上循环

相关问题 更多 >