我如何实现这样的功能中位数如果我有一个Python中有两个键的字典呢?

2024-09-27 02:27:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个文件夹中有许多文件,如下所示: enter image description here

我正在尝试实现一个数据字典。我对用2个键创建它感兴趣(第一个是http地址,第二个是第三个字段(使用插件),比如adblock)。这些值被引用到不同的度量中,所以我的目的是在字典实现之后,计算每个站点的平均值、中位数和方差。例如,对于平均值,我的意图是考虑文件中所有第4个字段的值,等等。我试图编写此代码,但首先,我不确定它是否正确。 enter image description here

我读了别人的帖子,但没有人解决我的问题,因为他们威胁或只有一个键,或者他们没有显示如何访问字典中的不同值来计算均值,中位数和方差。 问题很简单,承认dictionary实现是可以的,我必须以哪种方式访问key1的不同值:www.google.it->;键2:adblock? 任何形式的帮助都可以接受,我可以提供任何其他答案。你知道吗


Tags: 文件数据image文件夹http字典heredescription
1条回答
网友
1楼 · 发布于 2024-09-27 02:27:27

你可以用字典做你想做的事,但是你真的应该考虑使用Pandas库。这个库以称为“DataFrame”的表格数据结构为中心,它擅长于按列和按行计算,例如您似乎需要的计算。你知道吗

首先,这里是Pandas代码,它使用read_fwf()方法读取一个文本文件。它还显示第四列的平均值和方差:

# import the Pandas library:
import pandas as pd

# Read the file 'table.txt' into a DataFrame object. Assume
# a header-less, fixed-width file like in your example:
df = pd.read_fwf("table.txt", header=None)

# Show the content of the DataFrame object:
print(df)

# Print the fourth column (zero-indexed):
print(df[3])

# Print the mean for the fourth column:
print(df[3].mean())

# Print the variance for the fourth column:
print(df[3].var())

数据帧对象中有different ways of selecting columns and rows。前面示例中的方括号[ ]按列号选择了数据帧中的一列。如果只想从第三列中包含adblock的行中计算第四列的平均值,可以这样做:

# Print those rows from the data frame that have the value 'adblock'
# in the third column (zero-indexed):
print(df[df[2] == "adblock"])

# Print only the fourth column (zero-indexed) from that data frame:
print(df[df[2] == "adblock"][3])

# Print the mean of the fourth column from that data frame:
print(df[df[2] == "adblock"][3].mean())

编辑: 您还可以同时计算多个列的平均值或方差:

# Use a list of column numbers to calculate the mean for all of them
# at the same time:

l = [3, 4, 5]
print(df[l].mean())

结束编辑

如果要从多个文件中读取数据并对连接的数据进行计算,可以使用concat()方法。此方法获取DataFrame对象的列表并连接它们(默认情况下,按行)。使用以下行从目录中的所有*.txt文件创建数据帧:

df = pd.concat([pd.read_fwf(file, header=None) for file in glob.glob("*.txt")],
               ignore_index=True)

相关问题 更多 >

    热门问题