[英]Pandas - split column with dtype object (string) to dtype list by specifying delimiter
[英]store seconde column's values of a 3*2 array (dtype=object) in a list
給定以下數組
n=int(input())
a=np.empty((n,2) , dtype=object)
for i in range(n):
a[i][0]=input() #string
a[i][1]=input() #float
我想將所有浮點數收集到一個列表中,這樣我就可以進行一些操作。 這是我嘗試這樣做的方法:
def notes(a):
l=[]
for i in range(np.shape(a)[0]):
if a[i][1] not in l:
l.append(a[i][1])
return lis
這對我來說似乎合乎邏輯,但我收到了這個錯誤:
for i in range(np.shape(a)[0]): IndexError: 元組索引超出范圍
我怎樣才能解決這個問題?
你a
創作:
In [268]: n=int(input())
...: a=np.empty((n,2) , dtype=object)
...: for i in range(n):
...: a[i,0]=input() #string
...: a[i,1]=input() #float
...:
2
testing
1.23
foo
2.34
In [269]: a
Out[269]:
array([['testing', '1.23'],
['foo', '2.34']], dtype=object)
如果將此a
傳遞給notes
(您沒有顯示該步驟),則迭代應該有效:
In [270]: a.shape
Out[270]: (2, 2)
In [271]: a.shape[0]
Out[271]: 2
In [272]: for i in range(a.shape[0]):
...: print(a[i,1])
...:
1.23
2.34
您的錯誤表明您正在將標量傳遞給notes
In [275]: np.shape(4)[0]
Traceback (most recent call last):
Input In [275] in <cell line: 1>
np.shape(4)[0]
IndexError: tuple index out of range
但是您無需迭代即可獲得第二列:
In [276]: a[:,1]
Out[276]: array(['1.23', '2.34'], dtype=object)
In [277]: a[:,1].astype(float)
Out[277]: array([1.23, 2.34])
In [278]: a[:,1].astype(float).tolist()
Out[278]: [1.23, 2.34]
您重復使用a[i][0]
語法表明您沒有閱讀很多基本的numpy
文檔。 您將a
視為嵌套列表。 a[i,0]
是一種更慣用的索引二維數組的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.