Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple Average
#1
I'm new to Python and I want to start using it vs. using Excel.  

At the moment, I want to calculate the average selling price using a comma separated file that looks similar to this:

Filename:  pricelist.txt

Part Number      Amount
        A                   10
        A                   12
        A                   19
        A                   12
        B                   19
        B                   13
        B                   10

I want to see the output to look similar to this:
Part Number    Amount
        A               13.25
        B               14

How would I write code to do this?

Thanks a million in advance!!!!

Regards,

Dan
Reply
#2
what have you tried? show us some code and ask specific questions.
This sounds very much like homework.
Reply
#3
Not homework.  Wish I was back in school.  I have a New Years resolution to learn Python and use it at work whenever I can.  I deal with very large data sets and often the records exceed the 1M mark to use in Excel.  Any suggestions would be appreciated.
  
Here is the code I wrote.  Yes it's poor I know.

f = open("pricelist.txt", "r")

SSPList = {}

for line in f:
    entry = line.strip().split(",")
    PartNo = entry[0]
    Price = entry[1]
    AvgPrice = sum(Price)/len(SSPlist)
f.close()

print(SSPList)


and here is my error message:

Traceback (most recent call last):
  File "C:/Python34/Scripts/SSPTest.py", line 8, in <module>
    Price = entry[1]
IndexError: list index out of range

Ok, so I messed with it a little more, but I struggle with how to calculate the average.  Here is my new code and error message:

f = open("pricelist.csv", "r")

SSPList = {}

for line in f:
    entry = line.strip().split(",")
    PartNo = entry[0]
    print(PartNo)
    Price = entry[1]
    print(Price)
    AvgPrice = sum(Price)/len(SSPlist)
    SSPList[PartNo] = AvgPrice

f.close()

print(SSPList)



Error message:
>>> 
A
10
Traceback (most recent call last):
  File "C:\Python34\Scripts\SSPTest.py", line 11, in <module>
    AvgPrice = sum(Price)/len(SSPlist)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
Reply
#4
It's not poor. Not ideal, but reasonably good attempt at the problem. Let's solve it step by step.
It's look like your input file is not comma separated. Add print to see what you are working with
Also it's good to use with when opening file (that's called context manager).

with open("pricelist.txt", "r") as f:
   for line in f:
       print line # check what you get
       entry = line.strip().split(",")
       print entry # check what you have done
       # normaly you will unpack like this:
       # PartNo, Price = line.strip().split(",")

OK. Now you read the file. What you get is always str. You need to convert to float/int in order to make calculations (i.e. sum).
Also note that you don't add anything to SSPList dict. So you are not able to calculate average.
Reply
#5
Looks like homework to me too.
However, I don't think you've allowed using third party modules like Pandas for instance.

In [1]: from io import StringIO

In [2]: import pandas

In [3]: in_file = StringIO("""Part Number,Amount
   ...: A,10
   ...: A,12
   ...: A,19
   ...: A,12
   ...: B,19
   ...: B,13
   ...: B,10
   ...: """)

In [4]: data = pandas.read_csv(in_file, sep=',') # read_csv('file.csv')

In [5]: byPN = data.groupby('Part Number')

In [6]: byPN.mean()
Out[6]: 
            Amount
Part Number        
A            13.25
B            14.00
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#6
Thank you for your feedback.  You are providing some good guidance that is forcing me to think about how the code behaves.  I have redone the code yet again and I feel like I a farther from the solution because I can't even create a dictionary with the information that is stored in the now csv file.  Any feedback below would be helpful.  It may look like homework, but I am trying to dumb down the example so it is easier for folks to help me out.  My loop is clearly not appending to the dictionary.

Filename:  pricelist.csv

Part Number      Amount
        A                   10
        A                   12
        A                   19
        A                   12
        B                   19
        B                   13
        B                   10

#Code:
#Create a dictionary.
SSPList = {}

#open a file that contains only the Part No and the price.
with open("pricelist.csv", "r") as f:

#Read each line in the file and add the items to the dictionary above.
    for line in f:
        PartNos, Price = line.strip().split(",")
        Entry = {PartNos: str(Price)}
        SSPList.update(Entry)
    
print (SSPList) #Epic fail.  Only prints the last item for each unique PartNo.  What am I doing wrong?

#Calculate the average for each PartNo.  Can't do this until I fix the dictionary.

f.close()

#Output:
>>> 
{'A': '12', 'B': '10'}
>>>
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020