Python - ValueError: Cannot index with vector containing NA / NaN values
Python - ValueError: Cannot index with vector containing NA / NaN values
我正在尝试从数据框中获取包含单词列表中任何子字符串的产品的平均价格。我已经能够在多个电子表格上使用以下代码 -
dframe['Product'].fillna('', inplace=True)
dframe['Price'].fillna(0, inplace=True)
total_count = 0
total_price = 0
for word in ransomware_wordlist:
mask = dframe.Product.str.contains(word, case=False)
total_count += mask.sum()
total_price += dframe.loc[mask, 'Price'].sum()
average_price = total_price / total_count
print(average_price)
但是,其中一个电子表格在第 -
行抛出错误
dframe['Product'].fillna('', inplace=True)
与
ValueError: cannot index with vector containing NA / NaN values
我不明白为什么 dframe['Product'].fillna('', inplace=True)
没有处理这个问题。
急需帮助!谢谢!
如果第一行仍然失败,则可以通过参数 na=False
:
替换 str.contains
中条件中的 NaN
s
mask = dframe.Product.str.contains(word, case=False, na=False)
或尝试省略 inplace=True
并返回:
dframe['Product'] = dframe['Product'].fillna('')
解决索引问题的一种方法是实际使用 index
:
# define x
x = "Price"
# make sure to fill Na/NaN values
dframe[x] = dframe[x].fillna('00')
# identify rows that contain a specific value, returns a list of True/False
id_rows = dframe[x].str.contains(r"^ransom")
# save row index for identified rows, basically save all True
row_index = dframe.loc[id_rows].index
# update the chosen variable `x` with new value on identified rows using row index
dframe.loc[row_index, x] = 'cleaned'
这招行吗!
我正在尝试从数据框中获取包含单词列表中任何子字符串的产品的平均价格。我已经能够在多个电子表格上使用以下代码 -
dframe['Product'].fillna('', inplace=True)
dframe['Price'].fillna(0, inplace=True)
total_count = 0
total_price = 0
for word in ransomware_wordlist:
mask = dframe.Product.str.contains(word, case=False)
total_count += mask.sum()
total_price += dframe.loc[mask, 'Price'].sum()
average_price = total_price / total_count
print(average_price)
但是,其中一个电子表格在第 -
行抛出错误dframe['Product'].fillna('', inplace=True)
与
ValueError: cannot index with vector containing NA / NaN values
我不明白为什么 dframe['Product'].fillna('', inplace=True)
没有处理这个问题。
急需帮助!谢谢!
如果第一行仍然失败,则可以通过参数 na=False
:
str.contains
中条件中的 NaN
s
mask = dframe.Product.str.contains(word, case=False, na=False)
或尝试省略 inplace=True
并返回:
dframe['Product'] = dframe['Product'].fillna('')
解决索引问题的一种方法是实际使用 index
:
# define x
x = "Price"
# make sure to fill Na/NaN values
dframe[x] = dframe[x].fillna('00')
# identify rows that contain a specific value, returns a list of True/False
id_rows = dframe[x].str.contains(r"^ransom")
# save row index for identified rows, basically save all True
row_index = dframe.loc[id_rows].index
# update the chosen variable `x` with new value on identified rows using row index
dframe.loc[row_index, x] = 'cleaned'
这招行吗!