【问题标题】:Python. Finding thresholds for rows of dataPython。查找数据行的阈值
【发布时间】:2018-02-15 09:20:09
【问题描述】:

我是 Python 新手,但我必须解决以下任务。请帮帮我。

我有两个非常长的数据列表。对于每个列表,我必须找到一个阈值,它将列表划分为值 -1(低于阈值)和 +1(高于阈值)。为了找到两组数据之间的最佳相关性,我需要将两行分开。它必须是这样的:

List1 List2     List1 After Threshold applying  List2 After Threshold applying 
-50      -300     -1                             -1
-40      -200     -1                             -1
-30      -100     -1                             -1
-20      0        -1                             -1
-10      100       1                              1
0        200       1                              1
1        300       1                              1
2        400       1                              1

因此,在我的示例中,list1 的阈值为 -10(低于它的所有值都等于 -1,高于它的所有值都等于 1),list2 的阈值将是 100。

非常感谢!

【问题讨论】:

  • 你真是个令人困惑的人.....尝试学习 Python 语法和数据类型。这会有所帮助。
  • 你试过了吗?
  • 感谢您的回答。不得不说明,我的工作离Python很远,但是这个任务却出乎意料地发生在了我身上。到目前为止,我在 Python 中打开了我的文件,我认为我必须对 Loops 做一些事情,但是什么?
  • 我还使用行的平均值和中值作为阈值创建了错误矩阵。它给了我大约 0.70 的用户和生产者的准确度(平均比中位数好一点)。

标签: python math data-analysis


【解决方案1】:

查看python包pandas。这是一个教程:https://pandas.pydata.org/pandas-docs/stable/tutorials.html

import pandas as pd

list1 = [-50, -40, -30, -20, -10, 0, 1, 2]
list2 = [-300, -200, -100, 0, 100, 200, 300, 400]

df = pd.DataFrame({'List 1': list1, 'List 2': list2})

newdf = df.copy()
newdf[df > df.median()] = 1
newdf[df < df.median()] = -1

newdf 现在包含以下内容:

   List 1  List 2
0      -1      -1
1      -1      -1
2      -1      -1
3      -1      -1
4       1       1
5       1       1
6       1       1
7       1       1

如果您希望新旧列表并排,您可以连接数据框。首先重命名列也是一个好主意:

# rename columns:    
newdf = newdf.rename(columns=lambda x: x + ' after threshold')
# concatenate dataframes:
result = pd.concat([df, newdf], axis=1)

结果如下:

   List 1  List 2  List 1 after threshold  List 2 after threshold
0     -50    -300                      -1                      -1
1     -40    -200                      -1                      -1
2     -30    -100                      -1                      -1
3     -20       0                      -1                      -1
4     -10     100                       1                       1
5       0     200                       1                       1
6       1     300                       1                       1
7       2     400                       1                       1

【讨论】:

    猜你喜欢
    • 2014-02-06
    • 2022-01-08
    • 2021-06-19
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多