1

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

我有一个包含 3 列存储关键字的 Excel。我想阅读这些关键字并在 Pandas Dataframe 中进行搜索。下面的代码给了我一个错误:

    # 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

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

4

1 回答 1

1

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期望string来自kw[y]但得到float。解决方案可能很简单:

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

或者在你的情况下:

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

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

于 2021-09-06T10:12:09.510 回答