ValueError : 시퀀스로 배열 요소 설정
이 파이썬 코드 :
import numpy as p
def firstfunction():
UnFilteredDuringExSummaryOfMeansArray = []
MeanOutputHeader=['TestID','ConditionName','FilterType','RRMean','HRMean',
'dZdtMaxVoltageMean','BZMean','ZXMean','LVETMean','Z0Mean',
'StrokeVolumeMean','CardiacOutputMean','VelocityIndexMean']
dataMatrix = BeatByBeatMatrixOfMatrices[column]
roughTrimmedMatrix = p.array(dataMatrix[1:,1:17])
trimmedMatrix = p.array(roughTrimmedMatrix,dtype=p.float64) #ERROR THROWN HERE
myMeans = p.mean(trimmedMatrix,axis=0,dtype=p.float64)
conditionMeansArray = [TestID,testCondition,'UnfilteredBefore',myMeans[3], myMeans[4],
myMeans[6], myMeans[9], myMeans[10], myMeans[11], myMeans[12],
myMeans[13], myMeans[14], myMeans[15]]
UnFilteredDuringExSummaryOfMeansArray.append(conditionMeansArray)
secondfunction(UnFilteredDuringExSummaryOfMeansArray)
return
def secondfunction(UnFilteredDuringExSummaryOfMeansArray):
RRDuringArray = p.array(UnFilteredDuringExSummaryOfMeansArray,dtype=p.float64)[1:,3]
return
firstfunction()
이 오류 메시지가 발생합니다.
File "mypath\mypythonscript.py", line 3484, in secondfunction
RRDuringArray = p.array(UnFilteredDuringExSummaryOfMeansArray,dtype=p.float64)[1:,3]
ValueError: setting an array element with a sequence.
누구든지 오류 메시지가 표시되지 않도록 위의 깨진 코드에서 문제를 해결하기 위해 어떻게해야하는지 보여줄 수 있습니까?
편집 : 매트릭스의 내용을 얻기 위해 인쇄 명령을 수행했으며 이것이 인쇄 된 것입니다.
UnFilteredDuringExSummaryOfMeansArray는 다음과 같습니다.
[['TestID', 'ConditionName', 'FilterType', 'RRMean', 'HRMean', 'dZdtMaxVoltageMean', 'BZMean', 'ZXMean', 'LVETMean', 'Z0Mean', 'StrokeVolumeMean', 'CardiacOutputMean', 'VelocityIndexMean'],
[u'HF101710', 'PreEx10SecondsBEFORE', 'UnfilteredBefore', 0.90670000000000006, 66.257731979420001, 1.8305673000000002, 0.11750000000000001, 0.15120546389880002, 0.26870546389879996, 27.628261216480002, 86.944190346160013, 5.767261352345999, 0.066259118585869997],
[u'HF101710', '25W10SecondsBEFORE', 'UnfilteredBefore', 0.68478571428571422, 87.727887206978565, 2.2965444125714285, 0.099642857142857144, 0.14952476549885715, 0.24916762264164286, 27.010483303721429, 103.5237336525, 9.0682762747642869, 0.085022572648242867],
[u'HF101710', '50W10SecondsBEFORE', 'UnfilteredBefore', 0.54188235294117659, 110.74841107829413, 2.6719262705882354, 0.077705882352917643, 0.15051306356552943, 0.2282189459185294, 26.768787504858825, 111.22827075238826, 12.329456404418824, 0.099814258468417641],
[u'HF101710', '75W10SecondsBEFORE', 'UnfilteredBefore', 0.4561904761904762, 131.52996981880955, 3.1818159523809522, 0.074714285714290493, 0.13459344175047619, 0.20930772746485715, 26.391156337028569, 123.27387909873812, 16.214243779323812, 0.1205685359981619]]
나에게 5 행 x 13 열 행렬처럼 보이지만 다른 데이터가 스크립트를 통해 실행될 때 행 수는 가변적입니다. 내가 추가하는 것과 동일한 데이터로.
편집 2 : 그러나 스크립트에 오류가 발생했습니다. 그래서 나는 당신의 아이디어가 여기서 일어나는 문제를 설명한다고 생각하지 않습니다. 그래도 감사합니다. 다른 아이디어가 있습니까?
편집 3 :
참고로,이 문제 코드 줄을 교체하면 :
RRDuringArray = p.array(UnFilteredDuringExSummaryOfMeansArray,dtype=p.float64)[1:,3]
이것을 대신하여 :
RRDuringArray = p.array(UnFilteredDuringExSummaryOfMeansArray)[1:,3]
그런 다음 스크립트의 해당 섹션은 오류를 발생시키지 않고 정상적으로 작동하지만이 코드 줄은 줄을 더 아래로 내립니다.
p.ylim(.5*RRDuringArray.min(),1.5*RRDuringArray.max())
이 오류가 발생합니다.
File "mypath\mypythonscript.py", line 3631, in CreateSummaryGraphics
p.ylim(.5*RRDuringArray.min(),1.5*RRDuringArray.max())
TypeError: cannot perform reduce with flexible type
matplotlib에서 ylim을 사용하려면 데이터 유형을 지정해야하지만 데이터 유형을 지정하면이 게시물을 시작한 오류 메시지가 표시됩니다.
우리가 보여준 코드에서 우리가 말할 수있는 유일한 것은 다차원 배열과 모양이 다른 목록에서 배열을 만들려고한다는 것입니다. 예를 들어
numpy.array([[1,2], [2, 3, 4]])
또는
numpy.array([[1,2], [2, [3, 4]]])
입력 목록의 모양이 다차원 배열로 변환 될 수있는 (일반화 된) "상자"가 아니기 때문에이 오류 메시지가 나타납니다. 아마도 UnFilteredDuringExSummaryOfMeansArray
길이가 다른 시퀀스를 포함하고 있을 것입니다 .
Edit: Another possible cause for this error message is trying to use a string as an element in an array of type float
:
numpy.array([1.2, "abc"], dtype=float)
That is what you are trying according to your edit. If you really want to have a NumPy array containing both strings and floats, you could use the dtype object
, which enables the array to hold arbitrary Python objects:
numpy.array([1.2, "abc"], dtype=object)
Without knowing what your code shall accomplish, I can't judge if this is what you want.
The Python ValueError:
ValueError: setting an array element with a sequence.
Means exactly what it says, you're trying to cram a sequence of numbers into a single number slot. It can be thrown under various circumstances.
1. When you pass a python tuple or list to be interpreted as a numpy array element:
import numpy
numpy.array([1,2,3]) #good
numpy.array([1, (2,3)]) #Fail, can't convert a tuple into a numpy
#array element
numpy.mean([5,(6+7)]) #good
numpy.mean([5,tuple(range(2))]) #Fail, can't convert a tuple into a numpy
#array element
def foo():
return 3
numpy.array([2, foo()]) #good
def foo():
return [3,4]
numpy.array([2, foo()]) #Fail, can't convert a list into a numpy
#array element
2. By trying to cram a numpy array length > 1 into a numpy array element:
x = np.array([1,2,3])
x[0] = np.array([4]) #good
x = np.array([1,2,3])
x[0] = np.array([4,5]) #Fail, can't convert the numpy array to fit
#into a numpy array element
A numpy array is being created, and numpy doesn't know how to cram multivalued tuples or arrays into single element slots. It expects whatever you give it to evaluate to a single number, if it doesn't, Numpy responds that it doesn't know how to set an array element with a sequence.
In my case , I got this Error in Tensorflow , Reason was i was trying to feed a array with different length or sequences :
example :
import tensorflow as tf
input_x = tf.placeholder(tf.int32,[None,None])
word_embedding = tf.get_variable('embeddin',shape=[len(vocab_),110],dtype=tf.float32,initializer=tf.random_uniform_initializer(-0.01,0.01))
embedding_look=tf.nn.embedding_lookup(word_embedding,input_x)
with tf.Session() as tt:
tt.run(tf.global_variables_initializer())
a,b=tt.run([word_embedding,embedding_look],feed_dict={input_x:example_array})
print(b)
And if my array is :
example_array = [[1,2,3],[1,2]]
Then i will get error :
ValueError: setting an array element with a sequence.
but if i do padding then :
example_array = [[1,2,3],[1,2,0]]
Now it's working.
In my case, the problem was another. I was trying convert lists of lists of int to array. The problem was that there was one list with a different length than others. If you want to prove it, you must do:
print([i for i,x in enumerate(list) if len(x) != 560])
In my case, the length reference was 560.
for those who are having trouble with similar problems in Numpy, a very simple solution would be:
defining dtype=object
when defining an array for assigning values to it. for instance:
out = np.empty_like(lil_img, dtype=object)
In my case, the problem was with a scatterplot of a dataframe X[]:
ax.scatter(X[:,0],X[:,1],c=colors,
cmap=CMAP, edgecolor='k', s=40) #c=y[:,0],
#ValueError: setting an array element with a sequence.
#Fix with .toarray():
colors = 'br'
y = label_binarize(y, classes=['Irrelevant','Relevant'])
ax.scatter(X[:,0].toarray(),X[:,1].toarray(),c=colors,
cmap=CMAP, edgecolor='k', s=40)
참고URL : https://stackoverflow.com/questions/4674473/valueerror-setting-an-array-element-with-a-sequence
'Programing' 카테고리의 다른 글
Application 클래스를 확장해야하는 이유 (0) | 2020.06.03 |
---|---|
Visual Studio 2017에서 NUnit 테스트를 실행하는 방법은 무엇입니까? (0) | 2020.06.03 |
Git 브랜치를 자체 저장소로 옮기는 방법은 무엇입니까? (0) | 2020.06.03 |
Xcode에서 LLVM으로 디버깅하는 동안 변수 값을 변경하는 방법은 무엇입니까? (0) | 2020.06.03 |
MySQL의 varchar (max)와 동일합니까? (0) | 2020.06.03 |