按月份划分csv文件结果



我有一个csv文件,如下所示:

Date,Fruits,buy,sell
09/08/2019,apples,8,3
10/08/2019,oranges,10,6
10/08/2019,bananas,1,2
10/08/2019,kiwi,7,2
....
26/10/2020,pineapple,4,2
26/10/2020,watermelon,8,7
26/10/2020,grape,8,2
28/10/2020,apples,2,5
28/10/2020,oranges,6,1

我做了一个简单的代码,给我所有日期的盈利或非盈利天数。

file = csv.reader(open('csvfile.csv'))
next(file)
profit = 0
non_profit = 0
days = 0
for day in file:
days += 1
buy = int(day[2])
sell = int(day[3])
if buy < sell:
profit += 1
else:
non_profit += 1
print('In', (days), 'days , you have profit in', (profit), 'days, and', (non_profit), 'non profit days ')

我需要帮助找到盈利和非盈利的日子,按月。谢谢

因此,理解列表几乎完成了所有的工作。首先,你把所有的日子分成两个盈利和非盈利的日子列表,然后你只创建一个月的新列表,这样可以更容易地计算一个月中盈利/非盈利的天数。稍后,您将浏览月份列表,并创建月份编号和特定月份的盈利/非盈利天数的元组。最后,您可以将列表转换为字典,以便稍后在代码中使用。

import csv
file = csv.reader(open('test.txt'))
next(file)
#Get all lines/days from file
days = [day for day in file]
#Create list with profit and non profit days
days_profit = [d[0] for d in days if int(d[2]) < int(d[3])]
days_nonprofit = [d[0] for d in days if int(d[2]) > int(d[3])]
#Create list with month numbers only
m_p = [d.split('/')[1] for d in days_profit]
m_np = [d.split('/')[1] for d in days_nonprofit]
#Create list of tuples with month number and days in month which were profit/nonprofit
profit_days_per_month     = [(int(m), m_p.count(m)) for m in set(m_p)]
non_profit_days_per_month = [(int(m), m_np.count(m)) for m in set(m_np)]
#Additionally for future use you can convert it to dictionaries
profit_days_dict = dict(profit_days_per_month)
nonprofit_days_dict = dict(non_profit_days_per_month)
print(profit_days_dict)
print(nonprofit_days_dict)

最新更新