首页 > 解决方案 > Python。TypeError:“str”和“int”的实例之间不支持“<”

问题描述

from google.colab import drive
drive.mount('/content/drive')
% cd/content/drive/My Drive/data

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

data = pd.read_csv("d.csv", dtype=str, sep='\t')

print(data)

column1 = data["Num_c"]
column2 = data["Num_d"]

x = np.array(column1)
y = np.array(column2)

np.where(y < 0)

所以我有两个数组,我想使用 np.where() 但它说

TypeError: '<' not supported between instances of 'str' and 'int'.

如何将其转换为 int?

另外,如何使用 np.where() 从两个数组中删除前 5 个数据?

更新:

print(x) 
# [1] ['48' '65' '124' '201' '294' '443' '574' '833' '1290' '1978' '2747' '4518' '5977' '7714' '9695' '11794' '14383' '17072' '20050' '23282' '26767' '30506']

print(y)
# [2] ['0' '0' '0' '4' '7' '10' '18' '26' '42' '57' '81' '107' '133' '171' '214''260' '305' '355' '407' '461' '518' '577']

update2: 我不得不使用,dtype= str因为文件中的第一列是一个字符串

标签: python

解决方案


初始化 y 时,使用int dtype.

y = np.array(column2, dtype=int)

关于删除 from np.array,你可以像普通列表一样拼接它们,所以y[5:]会给你一个没有前 5 个元素的新数组。您也可以在初始化时执行此操作

x = np.array(column1)[5:]
y = np.array(column2)[5:]

推荐阅读