Read data from Excel and search it in df, TypeError: 'in <string>' requires string as left operand, not float

Read data from Excel and search it in df, TypeError: 'in <string>' requires string as left operand, not float

我阅读了很多有关此错误的信息,但找不到适合我的解决方案。

我有一个包含 3 列的 Excel,我在其中存储关键字。我想阅读这些关键字并在 Pandas 数据框中搜索它。下面的代码给我一个错误:

    # Error 
    if Keywords_EKN[y] in df.iloc[x, 12]:
    TypeError: 'in <string>' requires string as left operand, not float

代码:

    df_Dienstleister = pd.read_excel('Dienstleister.xlsx', header=None)
    Keywords_Dritte = df_Dienstleister.values.T[0].tolist()
    Keywords_EDT = df_Dienstleister.values.T[1].tolist()
    Keywords_EKN = df_Dienstleister.values.T[2].tolist()

    # Search for Keywords in df and replace some new data
    # There is another Excel in df
       for x in range(0, rows-1):
           for y in range(0, number_of_Keywords_EKN):
               if Keywords_EKN[y] in df.iloc[x, 12]:
                   df.iloc[x, 13] = "EKN"
           for z in range(0, number_of_Keywords_EDT):
               if (Keywords_EDT[z] in df.iloc[x, 12]):  
                   df.iloc[x, 13] = "EDT"
           for w in range(0, number_of_Keywords_Dritte):
               if  (Keywords_Dritte[w] in df.iloc[x, 12]) :
                  df.iloc[x, 13] = "Dritte"

但是当我只阅读 Excel 的一列并在代码中写入另一个关键字时,它工作正常:(我在 EKN 和 EDT 中有更多关键字,这只是为了显示我的问题)

Keywords_Dritte = df_Dienstleister.values.T[0].tolist()
Keywords_EKN = ['EKN']
Keywords_EDT = ['EDT']

print(Keywords_EKN[y]) 的输出是

EKN
nan

我不知道,有什么问题。感谢您的帮助。

您的 EKN 包含 np.nan,这是 float 值(或任何其他非字符串值)。您可以使用如下代码调用错误:

import numpy as np
import pandas as pd

kw = ['EKN', np.nan] # or 2, 2.3,...any non-string value
df = pd.DataFrame({'vals': ["EKN", "KNE", "xs"]})

for y in range(0, len(kw)):
    if kw[y] in df.iloc[0, 0]:
        print('found')

结果错误,因为 in 期望 kw[y] 得到 string 但得到 float。解决方案可能非常简单:

if str(kw[y]) in df.iloc[0, 0]:

或者您的情况:

if str(Keywords_EKN[y]) in df.iloc[x, 12]:

或按照 Timus 在评论中的建议替换开头数据框中的 nan 值。