首页 > 解决方案 > 如何使用 Python 和 Pandas 将 csv 文件中一个单元格的值复制到另一个 csv 文件?

问题描述

我正在关注这个Datafish 教程,因为我的任务是更新价目表。一个数据框中有超过 5000 行(目标)数据,另一个数据框中有 900 行(源)。我被困在如何添加(在本教程的上下文中)通过将两个数据帧与第二个数据帧进行比较以更新第二个数据帧所产生的差异。有人可以指出我应该前进的方向,哪种方法或如何添加东西的片段。

此处教程的片段创建了一个价格差异列(第二行)。我想获取该结果并将其添加到 Price2 列,或者如果有一种方法可以简单地使用在第一行中创建的 True/False 逻辑并将 Price1 复制到 Price2。

df1['pricesMatch?'] = np.where(df1['Price1'] == df2['Price2'], 'True', 'False')
df1['priceDiff?'] = np.where(df1['Price1'] == df2['Price2'], 0, df1['Price1'] - df2['Price2'])

示例数据框

firstProductSet = {'Product1': ['Computer','Phone','Printer','Desk'],
                   'Price1': [1200,800,200,350]}
df1 = pd.DataFrame(firstProductSet,columns= ['Product1', 'Price1'])


secondProductSet = {'Product2': ['Computer','Phone','Printer','Desk'],
                    'Price2': [900,800,300,350]}
df2 = pd.DataFrame(secondProductSet,columns= ['Product2', 'Price2'])

标签: pythonpandasdataframe

解决方案


IIUC 然后我会合并产品然后计算差异:

# Sample data
firstProductSet = {'Product1': ['Computer','Phone','Printer','Desk'],
                   'Price1': [1200,800,200,350]}
df1 = pd.DataFrame(firstProductSet,columns= ['Product1', 'Price1'])

secondProductSet = {'Product2': ['Computer','Phone','Printer','Desk'],
                    'Price2': [900,800,300,350]}
df2 = pd.DataFrame(secondProductSet,columns= ['Product2', 'Price2'])

# merge your frames together on products
df_m = df1.merge(df2, left_on='Product1', right_on='Product2')
# use .diff to calculate the difference in price
df_m['diff'] = df_m[['Price2', 'Price1']].diff(axis=1)['Price1']

   Product1  Price1  Product2  Price2   diff
0  Computer    1200  Computer     900  300.0
1     Phone     800     Phone     800    0.0
2   Printer     200   Printer     300 -100.0
3      Desk     350      Desk     350    0.0

此外,使用合并的原因是因为np.where将比较具有相同索引的数据,因此如果产品没有相同的索引,您将无法获得预期的结果。例如,如果我们将 df2 中的计算机从索引 0 移动到索引 3。

firstProductSet = {'Product1': ['Computer','Phone','Printer','Desk'],
                   'Price1': [1200,800,200,350]}
df1 = pd.DataFrame(firstProductSet,columns= ['Product1', 'Price1'])

secondProductSet = {'Product2': ['Phone','Printer','Desk', 'Computer'],
                    'Price2': [800,300,350,900]}
df2 = pd.DataFrame(secondProductSet,columns= ['Product2', 'Price2'])

然后,当您这样做时,np.where(df1['Price1'] == df2['Price2'], 'True', 'False')每个结果都将是错误的。


推荐阅读