英文:
Calculate average from CSV
问题
我是新手学习Python,尝试计算一些平均值。
我有一个包含以下数据的CSV文件:
网络,结果
网络1,100
网络2,200
网络3,300
网络1,101
网络2,202
网络3,303
我如何计算网络1、网络2和网络3的平均值,并创建另一个包含以下数据的CSV文件:
网络,平均值
网络1,105
网络2,201
网络3,301.5
看起来似乎很简单,但我正在为此苦苦思索。
提前感谢!
英文:
I am new to Python and im trying to calculate some averages.
I have a CSV with the following data:
Network,Result
Network 1,100
Network 2,200
Network 3,300
Network 1,101
Network 2,202
Network 3,303
How can i calculate the average for Network 1,Network 2 and Network 3 and create another CSV with the following data:
Network,Average
Network 1,105
Network 2,201
Network 3,301.5
Is seems pretty easy, but im breaking my head over this.
Thnx in advance!
答案1
得分: 3
这是一种方法:
import pandas as pd
df = pd.read_csv(path_to_csv)
(df
.groupby('Network')['Result'].mean()
.rename(columns={"Result": "Average"})
.reset_index()
.to_csv("agg.csv", index=False))
Network Average
0 Network 1 100.5
1 Network 2 201.0
2 Network 3 301.5
英文:
Here's a way to do:
import pandas as pd
df = pd.read_csv(path_to_csv)
(df
.groupby('Network')['Result'].mean()
.rename(columns={"Result": "Average"})
.reset_index()
.to_csv("agg.csv", index=False))
Network Average
0 Network 1 100.5
1 Network 2 201.0
2 Network 3 301.5
答案2
得分: 1
如果你经常与数据库工作,可能会更喜欢编写SQL而不是重新发明轮子。我发现这是最容易理解的:
import pandas as pd
import pandasql as ps
mydata = pd.DataFrame([
['Network 1',100]
,['Network 2',200]
,['Network 3',300]
,['Network 1',101]
,['Network 2',202]
,['Network 3',303]]
,columns=['Network','Result'])
mysql = """
select Network,avg(Result) as avgresult
from mydata
group by Network
"""
print(ps.sqldf(mysql))
返回:
Network avgresult
0 Network 1 100.5
1 Network 2 201.0
2 Network 3 301.5
英文:
If you work with databases a lot, you might prefer writing SQL instead of reinventing the wheel. I find this to be the easiest to understand:
import pandas as pd
import pandasql as ps
mydata = pd.DataFrame([
['Network 1',100]
,['Network 2',200]
,['Network 3',300]
,['Network 1',101]
,['Network 2',202]
,['Network 3',303]]
,columns=['Network','Result'])
mysql = """
select Network,avg(Result) as avgresult
from mydata
group by Network
"""
print(ps.sqldf(mysql))
returns:
Network avgresult
0 Network 1 100.5
1 Network 2 201.0
2 Network 3 301.5
答案3
得分: 1
Pandas提供了各种从文件中读取数据的方法。
read_csv()
是其中之一。
这是您任务的解决方案。
# 导入Pandas库
import pandas as pd
# 从文件系统中读取CSV文件。
csv = pd.read_csv("data/temp1.csv")
# 您的语句表示您需要独特的网络数据,并对值进行平均处理。
# 对于学习,您可以根据需要在groupby子句中添加多个列名。
# 您还可以在agg函数中使用不同的聚合函数,如count、sum等。再次提醒,这是一个列表,因此可以同时传递多个聚合函数。
newds = csv.groupby(['Network'])['Result'].agg(['mean']).reset_index()
# 最后将您的数据集转换为CSV文件并保存到文件系统中。
newds.to_csv('new_csv.csv', index=False)
英文:
Pandas provide various methods of reading data from Files.
read_csv()
is one of them
Here is the solution to your task.
# Importing Pandas Library
import pandas as pd
# Reading the CSV file from the File system.
csv = pd.read_csv("data/temp1.csv")
# Your statement says your need unique Network data and average over the values.
# For your learning, you can add multiple column names in groupby clause according to your requirement.
# You can also use different aggregation like count, sum etc. in agg function. Again its a list hence you can pass multiple aggregations at the same time.
newds = csv.groupby(['Network'])['Result'].agg(['mean']).reset_index()
# Finally converting your dataset to csv file and saving it into the File System.
newds.to_csv('new_csv.csv', index=False)
答案4
得分: -1
import csv
from collections import defaultdict
with open("data.csv", newline='', mode='r') as csvfile:
reader = csv.reader(csvfile, delimiter=' ')
networks = defaultdict(lambda: [0,0])
for row in reader:
if len(row) == 1:
continue
else:
network_num, value = row[1].split(",")
networks[network_num][0] += int(value)
networks[network_num][1] += 1
with open("answer.csv", newline='', mode="w") as output:
writer = csv.writer(output, quoting=csv.QUOTE_NONE)
writer.writerow(["Network", "Average"])
for k,v in networks.items():
average = v[0] / v[1]
writer.writerow([f'Network {k}', average])
output:
Network,Average
Network 1,100.5
Network 2,201.0
Network 3,301.5
this will output a csv file in the format you want.
defaultdict is a datatype that is similar to a dictionary, except if you attempt to access a key that does not exist yet, a default value is provided for that key so you don't get a key error.
<details>
<summary>英文:</summary>
import csv
from collections import defaultdict
with open("data.csv", newline='', mode='r') as csvfile:
reader = csv.reader(csvfile, delimiter=' ')
networks = defaultdict(lambda: [0,0])
for row in reader:
if len(row) == 1:
continue
else:
network_num, value = row[1].split(",")
networks[network_num][0] += int(value)
networks[network_num][1] += 1
with open("answer.csv", newline='', mode="w") as output:
writer = csv.writer(output, quoting=csv.QUOTE_NONE)
writer.writerow(["Network", "Average"])
for k,v in networks.items():
average = v[0] / v[1]
writer.writerow([f'Network {k}', average])
output:
Network,Average
Network 1,100.5
Network 2,201.0
Network 3,301.5
this will output a csv file in the format you want.
**defaultdict** is a datatype that is similar to a dictionary, except if you attempt to access a key that does not exist yet, a default value is provided for that key so you don't get a key error.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论