我有一个包含多行产品的 csv,例如
SKU;price;availability;Time;Supplier;CatCode
x1;10.00;0;1-4-2019;sup1;K1
x1;10.00;0;1-4-2019;sup1;K3
x1;10.00;0;1-4-2019;sup1;K2
还有一个 csv
CATCODE;MARGIN
K1;0.08
我尝试使用以下代码仅更新列表行中的一个元素,其中每个 csv 的 catcode 都匹配。在这种情况下,它应该只更新 K1,而其他值保持不变。这是我尝试过的:
def ChangeToFinalCSV():
SetFixMinPrices = SetFixPrices()
CatCodes = GetCatCodes()
for FixMinPrice in SetFixMinPrices:
for cat in CatCodes:
if cat[0] == FixMinPrice[5]:
FixMinPrice[1] = (((float(FixMinPrice[1].replace(',','.').replace('€','')) + float(SupplierShipping)) * float(BankingComission))*(1+float(cat[1]))) * float(1.24)
FixMinPrice[1] = "{:.2f}".format(FixMinPrice[1])
FixMinPrice[1] = str(FixMinPrice[1]).replace('.',',') + ' €'
retailed.append(FixMinPrice)
return retailed
retailed = ChangeToFinalCSV()
但这段代码改变了所有元素,而不仅仅是以 K1 为 CatCode 的行
我想用 enumerate of Python 来做,但我不知道怎么做。如何仅更新两个文件中的 catcode 匹配的位置?我想用公式 new_price=price(1+margin)
将价格乘以利润。
我尝试拥有一个像最初的 csv 而不是 pandas 表
喜欢
SKU;price;availability;Time;Supplier;CatCode
x1;10.80;0;1-4-2019;sup1;K1
x1;10.00;0;1-4-2019;sup1;K3
x1;10.00;0;1-4-2019;sup1;K2
最佳答案
这可以通过 pandas 使用 merge 来完成.
import pandas as pd
import numpy as np
#put you file path here instead of mine
#Just change the stuff in quotes to the path where the csvs
#you want to process are, making sure to inlclude the correct names
#csv1 should have the bigger dataset, csv2 is just the margin and catcode
csv1_filename='U:/PLAN/BCUBRICH/Python/Tests/merge_test/csv1.txt'
csv2_filename='U:/PLAN/BCUBRICH/Python/Tests/merge_test/csv2.txt'
df1=pd.read_csv(csv1_filename, sep=';') #save first csv as dataframe
df2=pd.read_csv(csv2_filename,sep=';') #save second csv as dataframe
#merge the two so that if there is a catcode in the second file the new
#column margin will be filled with the correct value
df_final=df1.merge(df2, left_on='CatCode',right_on='CATCODE', how='outer')
df_final['price']=np.where(df_final['MARGIN'].isnull(),df_final['price'],df_final['price']*(1+df_final['MARGIN'])*1.24)
df_final.to_csv('your_path\file_name_you_want.txt', sep=';',index=False)
这是您的原始 csv。
这是合并数据帧的最终输出。
关于python - 如何使用来自另一个 csv 的信息更新 csv 的一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55480866/