【问题标题】:CSV: how to create a list from rows and find closest value of the list from the list containing lists?CSV:如何从行创建列表并从包含列表的列表中查找列表的最接近值?
【发布时间】:2021-08-29 16:45:32
【问题描述】:

我的代码读取 CSV 文件中的一列,该文件包含 3 列:区域、离线呼叫和流量。

如果您需要复制/粘贴数据。这是每列的前 10 行。

网外电话:0、421、667、12146、7163、5211、1374、3702、1129、2679、4279

流量:0、30167、23172、215033、126514、130045、75357、257846、77677、79331

我需要“Offnet Calls”和“Traffic”来创建列表。例如,第 3 行将是 [421, 30167] 并从包含相同参数列表的列表中搜索最佳匹配/最接近的值。 看代码就更清楚了:


tp_usp15 = [10, 200]
tp_usp23 = [15, 250]
tp_usp27 = [20, 300]
list_usp = [tp_usp15,tp_usp23, tp_usp27]

tp_bsnspls_s = [1,30]
tp_bsnspls_steel = [13,250]
tp_bsnspls_chrome = [18,350]
list_bsnspls = [tp_bsnspls_s,tp_bsnspls_steel,tp_bsnspls_chrome]

tp_bsnsrshn10 = [10,200]
tp_bsnsrshn15 = [15,300]
tp_bsnsrshn20 = [20,400]
list_bsnsrshn = [tp_bsnsrshn10,tp_bsnsrshn15,tp_bsnsrshn20]

common_list = list_usp + list_bsnspls + list_bsnsrshn

例如,从代码中提供的这个列表中,第 3 行 = [421, 30167] 的最接近值/最佳匹配是 [20, 400] = tp_bsnsrshn20。我需要一个代码来对 CSV 文件中的所有值进行相同的操作。需要将最接近的值/最佳匹配记录到下一列(应在“流量”列旁边创建一个名为“最佳匹配”的新列)。我有一个适用于输入的代码。 2 个用户输入创建一个列表,并从列表列表中完成搜索。

client_traffic = int(input("Enter the expected monthly traffic: "))
client_offnet = int(input("Enter monthly offnet calls: "))
list_client = [client_payment, client_offnet]

from functools import partial
def distance_squared(x, y):
    return (x[0] - y[0])**2 + (x[1] - y[1])**2
best_match_overall = min(common_list, key=partial(distance_squared, list_client))
name_best_match_overall = [k for k,v in locals().items() if v == best_match_overall][0]

如何将此代码应用于整个 CSV 文件。顺便说一句,它还给出了值的名称。我想高级用户应该不难创建一些循环,该循环将按照我在上一个代码中提供的相同概念工作,但适用于整个文件。

【问题讨论】:

  • 要仔细检查,您正在尝试读取一个包含两列的 CSV 文件,并且您试图在 CVS 文件中找到与给定值的每一行最接近的正确值对,对吗?跨度>
  • @Mazen 正确!请问有什么代码思路吗?
  • 我会马上处理的。

标签: python list csv


【解决方案1】:

更新 2.0

您需要将数据存储到这样的文件(common_list)中:

import numpy as np
import pandas as pd
# create data
common_list = {
    "common_name": ["tp_usp15","tp_usp23","tp_usp27","tp_bsnspls_s","tp_bsnspls_steel","tp_bsnspls_chrome","tp_bsnsrshn10","tp_bsnsrshn15","tp_bsnsrshn20"],
    "common_Offnet": [10,15,20,1,13,18,10,15,20],
    "common_Traffic": [200,250, 300,30,250,350,200,300,400]
}
common_list = pd.DataFrame.from_dict(common_list)
common_list.to_csv ('common_list.csv', index = False, header=True)

然后通过运行以下命令来做你想做的事:

import numpy as np
import pandas as pd

common_list = pd.read_csv("common_list.csv")
common_list_offnet = common_list["common_Offnet"].to_list()
common_list_traffic = common_list["common_Traffic"].to_list()

# convert csv_data to numpy array
array_offnet = np.array(common_list_offnet)
array_traffic = np.array(common_list_traffic)
array = np.column_stack((array_offnet,array_traffic))

# reading data
csv_data = pd.read_csv("test.csv")
#data = csv_data.drop(['Zone'], axis=1)
data = csv_data[['Offnet', 'Traffic']]
# convert csv_data to numpy array
data = data.to_numpy()

# get the closest points
sol = []
for target in data:
    # compute distance
    dist = np.sqrt((np.square(array[:,np.newaxis]-target).sum(axis=2)))
    # get the index of the lowest value
    idx =  np.argmin(dist)
    sol.append(idx)
# print answers
csv_data["best_name"] = common_list['common_name'][sol].values
csv_data["best_Offnet"] = common_list['common_Offnet'][sol].values
csv_data["best_Traffic"] = common_list['common_Traffic'][sol].values
csv_data.to_csv ('updated.csv', index = False, header=True)

为了便于您稍后处理,我已将最佳解决方案的两个值设置为两个不同的列,这样您就无需花时间预处理数据,这是一个烦人的过程。

更新答案

import pandas as pd
import numpy as np

...
common_list = list_usp + list_bsnspls + list_bsnsrshn

# convert csv_data to numpy array
array = np.array(common_list)

# reading data
csv_data = pd.read_csv("test.csv")
data = csv_data.drop(['Zone'], axis=1)
# convert csv_data to numpy array
data = data.to_numpy()

# get the closest points
sol = []
for target in data:
    # compute distance
    dist = np.sqrt((np.square(array[:,np.newaxis]-target).sum(axis=2)))
    # get the index of the lowest value
    idx =  np.argmin(dist)
    sol.append(idx)
# print answers
print(array[sol])
csv_data["index"] = sol
csv_data["values"] = array[sol].tolist()
csv_data.to_csv ('updated.csv', index = False, header=True)

旧答案

这是一个测试代码的示例(带有虚拟数据)。

import pandas as pd
import numpy as np

# reading data
csv_data = pd.read_csv("file.csv")

# convert csv_data to numpy array
array = csv_data.to_numpy()

# ask for target data
client_traffic = int(input("Enter the expected monthly traffic: "))
client_offnet = int(input("Enter monthly offnet calls: "))
example = [client_offnet, client_traffic]


answers = []
# convert example to numpy array
target = np.array(example)
# gets the index of the closest value
best_match_overall =  np.argmin(np.linalg.norm(array - target,keepdims=True))
answers.append(best_match_overall)

【讨论】:

  • 但是“Offnet call”和“Traffic”不受这 10 个值的限制。如屏幕截图所示,共有 2 列
  • 我已经用代码 sn-p 更新了答案,以获得你想要的东西。
  • 没有输入。离线呼叫和流量的值取自 CSV 文件的列
  • 我很困惑。您是否试图通过比较输入和 csv 数据来找到最接近的?你之前用correct回答了我的问题,我就是这么做的。
  • 看,我们有 2 个需要的列:Offnet call 和 Traffic。我在代码内部创建了一个比较列表。检查创建名为 common_list 的列表的第一个代码。我需要为 CSV 代码中的每一行从 common_list 中找到最佳匹配/最接近的值。请检查我提供的第一部分代码中的 common_list 是什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2012-11-14
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多