简体   繁体   中英

Merge a csv and txt file, then alphabetize and eliminate duplicates using python and pandas

I am trying to combine two csv files (items.csv and prices.csv) to create combined_list.txt. The result (combined_list.txt) should be a list sorted in alphabetical order in the format: item (quantity): $total_price_for_item and include 2 additional lines: a separator line with 10 equal signs and a line with the total amount for the list:

bread (10.0): $3.0
cheese (0.4): $4.0
eggs (11.0): $2.2
ham (0.6): $9.0
milk (2.0): $6.5
peanut butter (4.0): $12.0
tuna (4.0):$8.0
====================
Total: $44.7

items.csv looks like

eggs,6
milk,1
cheese,0.250
ham,0.250 
etc...

and prices.txt looks like

eggs,$0.2
milk,$3.25 
etc...

I have to do a version with python and another with pandas but nothing I find online hits the mark in a way I can work with. I started with

import csv 
with open('items.csv', 'r') as inputFile:
    new_file = csv.reader(inputFile, delimiter=' ', quotechar='|')
    for row in new_file:
        print .join(row)

But I am having trouble putting everything together. Some of the solutions I found are a little too complex for me or don't work with my files, which have no column headers. I'm still trying to figure it out but I know that for some of you this is super easy so I am turning to the collective wisdom instead of hitting my head against the wall alone.

Pandas has a built in method for reading csv files. Here is code to get both sets of data into one dataframe:

import pandas as pd    

items = pd.read_csv('items.csv', index_col=0)
items.columns = columns=['Item', 'QTY']
prices = pd.read_csv('prices.csv', index_col=0)
prices.columns = ['Item', 'Price']
df = items.combine_first(prices)

To sort and drop duplicates:

df = df.sort()
df.drop_duplicates('Item', inplace=True)
df = df.to_csv('combined.txt')    

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