简体   繁体   中英

Compare 2nd column of two files and compute the percentage increase or decrease

I want to compare file1(numeric value after the comma) to file2(numeric value after the comma) and display percentage increase or decrease.

file1.csv
item1,100   
item2,150
item3,250
item4,550
item5,400
item6,125

file2.csv
item1,160
item2,180
item3,190
item4,1100
item5,100
item6,510

Result.csv
item1 +60%
item2 +20%
item3 -24%
item4 +100%
item5 -75%
item6 +308%

You'll want to look into pandas for this one.

Something like this should work.

  1. Read in both data sets
  2. Merge them on the id column
  3. Calculate the difference
  4. Drop the columns we don't want anymore
  5. Write the result to CSV
import pandas as pd

data1 = pd.read_csv('file1.csv', header=None, names=['id', 'val_1'])
data2 = pd.read_csv('file2.csv', header=None, names=['id', 'val_2'])

data1 \
    .merge(data2, on = 'id') \
    .assign(result = lambda data: data.val_2/data.val_1 - 1) \
    .filter(['id', 'result']) \
    .to_csv('Result.csv', header=None, index = False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM