I need your help. I have a .csv "orders.csv" made in this way:
name | number_of_orders | eurosxp
fried chips 100 2
fried chicken 25 5
salad one 20 5
salad two 10 5
( and so on)
I'm trying to create a script in python to read this data and to do calculations, so with pandas, I'm trying to create a tab/list of values that I can recall in a framework...so I wrote this that doesn't work. Someone can help?
import numpy as np
import os
import math
import pandas as pd
class MenuNfeedback:
data = pd.read_csv("orders.csv", header=None)
def __init__(self) -> None:
def name_dishes(self):
'''dishes name'''
for j in range(0, (self.data.iloc[j][0])):
nameDishes = list(str(j) )
return nameDishes
def numb_ord(self):
'''How many times was orderes'''
orderNumb_list=[]
orderNumb=self.data.iloc[i][1]
for i in range(0, len(self.data.iloc[i][1])):
orderNumb=self.data.iloc[i][1]
orderNumb_list.append(orderNumb)
return carbon_list
def eurosxp(self):
'''List of prices'''
prices_f=[]
for i in range(0, len(self.data.iloc[i][1])):
prices_f.append(self.data.iloc[i][2])
return prices_f
I see many errors and I started from few time to use/call functions
Thank you
CodePudding user response:
Your orders.csv
file
name | number_of_orders | eurosxp
fried chips 100 2
fried chicken 25 5
salad one 20 5
salad two 10 5
is not comma separated, so pd.read_csv("orders.csv", header=None)
will not give expected DataFrame, you could get well-formed DataFrame following way
import pandas as pd
df = pd.read_csv('orders.csv', header=None, sep=' {2,}', names=["name","number_of_orders","eurosxp"], skiprows=1)
print(df.shape)
print(df)
gives output
(4, 3)
name number_of_orders eurosxp
0 fried chips 100 2
1 fried chicken 25 5
2 salad one 20 5
3 salad two 10 5
Explanation: I ignore 1st line of file and provide names of columns directly, I set separator to regular expressions meaning 2 or more spaces. EDIT: code ameloriated as suggested in comment
CodePudding user response:
You can also read the file as fixed width formatted
if the widths are consistent:
pd.read_fwf("orders.csv", colspecs=[(0,14),(16, 33),(35,42)])
Output:
name number_of_orders eurosxp
0 fried chips 100 2
1 fried chicken 25 5
2 salad one 20 5
3 salad two 10 5