簡體   English   中英

努力正確利用str.find()函數

[英]Struggling to correctly utilize the str.find() function

我正在嘗試使用str.find() ,並且不斷出現錯誤,我在做什么錯?

我有一個矩陣,其中第一列是數字,第二列是分配給這些字母的縮寫。 縮寫是ED,LI或NA,我試圖找到與這些字母相對應的位置,以便我可以繪制一個散點圖,該散點圖用顏色編碼以匹配這3個組。

mat=sio.loadmat('PBMC_extract.mat') #loading the data file into python
data=mat['spectra']
data_name=mat['name'] #calling in varibale
data_name = pd.DataFrame(data_name) #converting intoa readable matrix

pca=PCA(n_components=20)  # preforms pca on data with 20 components
pca.fit(data) #fits to data set
datatrans=pca.transform(data)  #transforms data using PCA

# plotting the graph that accounts for majority of data and noise
plt.plot(np.cumsum(pca.explained_variance_ratio_))
plt.xlabel('Number of components')
plt.ylabel('Cumulative explained variance')


fig = plt.figure()
ax1 = Axes3D(fig)

#str.find to find individual positions of anticoagulants
str.find(data_name,'ED')

#renaming data for easiness
x_data=datatrans[0:35,0]
y_data=datatrans[0:35,1]
z_data=datatrans[0:35,2]

x2_data=datatrans[36:82,0]
y2_data=datatrans[36:82,1]
z2_data=datatrans[36:82,2]

x3_data=datatrans[83:97,0]
y3_data=datatrans[83:97,1]
z3_data=datatrans[83:97,2]

# scatter plot of score of PC1,2,3
ax1.scatter(x_data, y_data, z_data,c='b', marker="^")
ax1.scatter(x2_data, y2_data, z2_data,c='r', marker="o")
ax1.scatter(x3_data, y3_data, z3_data,c='g', marker="s")

ax1.set_xlabel('PC 1')
ax1.set_ylabel('PC 2')
ax1.set_zlabel('PC 3')


plt.show()

不斷出現的錯誤如下:

  File "/Users/emma/Desktop/Final year project /working example of colouring data", line 49, in <module>
    str.find(data_name,'ED')

TypeError: descriptor 'find' requires a 'str' object but received a 'DataFrame'

該錯誤是因為find方法期望使用str對象而不是DataFrame對象。 正如PiRK提到的那樣,問題在於您要在此處替換data_name變量:

data_name = pd.DataFrame(data_name)

我認為應該是:

data = pd.DataFrame(data_name)

同樣,盡管str.find(data_name,'ED')起作用,但建議的方法是僅傳遞搜索詞,如下所示:

data_name.find('ED')

正確的語法是

data_name.find('ED')

看這里的例子

https://www.programiz.com/python-programming/methods/string/find

編輯1盡管我只是注意到data_name是一個熊貓DataFrame,所以那行不通? 您到底想做什么?

您斷開的函數調用甚至沒有返回到變量? 所以很難回答您的問題?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM