FutureWarning: Setting an item of incompatible dtype is deprecated

问题描述:

使用Pandas库,DataFrame.apply()方法设置列数据格式,在回调函数中将int类型转为str类型。Pandas发出警告。这个警告不影响结果,类型转换成功了,就是看着不爽

测试代码:

import pandas as pd
import numpy as np

data = pd.DataFrame(np.random.randint(1, 10, size=(4, 3)))
def convert(df):
    df[1] = (df[1]+10).astype(str)
    df[2] = float(df[2] + 100)
    return df


data = data.apply(lambda df: convert(df), axis=1)
data[1].info

data结构:

运行结果

只是发出警告,并不影响运行结果。

FutureWarning: Setting an item of incompatible dtype is deprecated and will raise an error in a future version of pandas. Value '11' has dtype incompatible with int32, please explicitly cast to a compatible dtype first.

解决方法

不在convert()中转换,在apply()执行完后进行转换

完整代码

import pandas as pd
import numpy as np

data = pd.DataFrame(np.random.randint(1, 10, size=(4, 3)))
def convert(df):
    df[1] = df[1]+10
    df[2] = float(df[2] + 100)
    return df


data = data.apply(lambda df: convert(df), axis=1)
data[1] = data[1].astype(str)

运行结果

D:\python312\python.exe D:\py文件\try1.py D:\py文件\try1.py:35: FutureWarning: Setting an item of incompatible dtype is deprecated and will raise an error in a future version of pandas. Value 'neg' has dtype incompatible with int64, please explicitly cast to a compatible dtype first. data.loc[data['评论类型'] == 1, '评论类型'] = 'neg' 评论内容 评论类型 0 外形外观:非常好看,老婆非常喜欢\n屏幕音效:效果好\n拍照效果:绝对高清,效果很好\n运行... pos 1 外形外观:外形外观:包装非常完好,信任京东!非常靓丽的外形。握在手里很舒适。\n拍照效果:拍... pos 2 外形外观:这个整体外观还是不错的,比较新颖,而且很时尚。\n运行速度:速度方面现在还是很流畅... pos 3 外形外观:非常炸眼的配色,选就选这个颜色,亮晶晶,出众!\n拍照效果:拍照效果很好,主打,摄... pos 4 手机终于到了 一大早就给送来了 给媳妇买的 手机非常漂亮 曲屏很有质感 媳妇很喜欢 用了一会... pos Building prefix dict from the default dictionary ... Loading model from cache C:\Users\陆非\AppData\Local\Temp\jieba.cache Loading model cost 1.926 seconds. Prefix dict has been built successfully. Traceback (most recent call last): File "D:\py文件\try1.py", line 340, in <module> Data_Ychuli() File "D:\py文件\try1.py", line 76, in Data_Ychuli stop_path = open("./data/stoplist.txt", 'r', encoding='UTF-8') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ FileNotFoundError: [Errno 2] No such file or directory: './data/stoplist.txt'为什么会报错
最新发布
03-25
<think>嗯,用户遇到了几个Python的问题,需要逐一解决。首先,FileNotFoundError是因为找不到'stoplist.txt'文件。可能需要检查文件路径是否正确,或者使用绝对路径。然后是pandasFutureWarning,提示要将int64转为object类型,这可能是因为数据中有混合类型,需要显式转换。还有jieba分词停止词路径错误的问题,同样需要检查路径是否存在,或者考虑将文件放在项目目录下。 首先处理FileNotFoundError。用户可能把'stoplist.txt'放在了错误的目录,比如当前工作目录不是脚本所在目录。建议使用绝对路径,或者用os模块动态获取当前脚本的路径。比如用os.path.dirname(__file__)来获取脚本所在目录,再拼接文件路径,这样更可靠。 接下来是pandasFutureWarning。当DataFrame中存在混合类型时,pandas可能会自动推断类型,但在未来版本中行为会改变。用户需要显式指定dtype='object',或者在读取数据时确保列的类型一致,比如使用converters参数或者处理数据中的混合类型。 然后是jieba分词的停止词路径错误。同样,路径问题,应该使用绝对路径或者正确的相对路径。如果停止词文件在项目子目录中,比如'data/stoplist.txt',要确保脚本运行时的工作目录正确,或者使用os.path来构建正确的路径。另外,处理文件是否存在,可以用os.path.exists检查,提前报错提示。 可能用户的项目结构有问题,或者文件没有正确放置。需要指导用户检查文件的实际位置,并调整代码中的路径引用。同时,异常处理也很重要,比如用try-except块捕获FileNotFoundError,并给出友好的提示。 另外,用户提到的stoplist.txt可能需要用正确的编码方式打开,比如指定encoding='utf-8',避免在读取时出现编码错误。还有,如果用户使用的是相对路径,当脚本被其他目录调用时,相对路径可能会出错,所以最好用绝对路径或者动态获取脚本所在目录。 总结解决方案的步骤:检查路径是否正确,使用绝对路径或动态路径,处理文件存在性,显式指定数据类型,异常处理和编码设置。这些步骤应该能解决用户的问题。</think>### 问题分析及解决方案 #### 1. **FileNotFoundError: './data/stoplist.txt' 路径错误** - **原因**:文件路径未正确指向 `stoplist.txt`,可能文件未放在项目目录的 `data` 子目录下,或路径分隔符不兼容。 - **解决方案**: 1. **检查文件位置**:确认 `stoplist.txt` 是否在 `./data/` 目录下,若目录不存在需手动创建。 2. **使用绝对路径**:将相对路径替换为绝对路径,例如: ```python stopwords_path = r'C:\project\data\stoplist.txt' # Windows示例 # 或 stopwords_path = '/home/user/project/data/stoplist.txt' # Linux/macOS示例 ``` 3. **动态路径处理**:通过 `os` 模块动态获取当前脚本路径: ```python import os script_dir = os.path.dirname(os.path.abspath(__file__)) stopwords_path = os.path.join(script_dir, 'data', 'stoplist.txt') ``` 4. **异常处理**:添加文件存在性检查: ```python if not os.path.exists(stopwords_path): raise FileNotFoundError(f"停止词文件 {stopwords_path} 未找到,请检查路径") ``` #### 2. **pandas FutureWarning: 建议将 int64 列转换为 object 类型** - **原因**:当 DataFrame 列包含混合类型(如整数和字符串)时,pandas 未来版本将不再自动推断为 `float`,建议显式指定 `dtype`。 - **解决方案**: 1. **显式指定列类型**: ```python df = pd.read_csv('data.csv', dtype={'column_name': 'object'}) ``` 2. **转换现有列类型**: ```python df['column_name'] = df['column_name'].astype('object') ``` 3. **处理缺失值**:若列包含 `NaN`,需填充或保留为 `object` 类型(如引用[3]中分组处理缺失值的示例)。 #### 3. **jieba 分词停止词路径错误** - **原因**:与 `FileNotFoundError` 类似,路径未正确指向停止词文件。 - **解决方案**: 1. **确保文件存在**:使用上述路径检查方法验证 `stoplist.txt` 位置。 2. **加载停止词示例代码**: ```python import jieba def load_stopwords(file_path): with open(file_path, 'r', encoding='utf-8') as f: return set([line.strip() for line in f]) stopwords = load_stopwords(stopwords_path) words = [word for word in jieba.cut(text) if word not in stopwords] ``` 3. **默认停止词替代方案**:若无自定义文件,可使用 `jieba` 内置停用词(需手动下载或引用公共资源)。 --- ### 代码示例整合 ```python import os import pandas as pd import jieba # 1. 动态设置停止词路径 script_dir = os.path.dirname(os.path.abspath(__file__)) stopwords_path = os.path.join(script_dir, 'data', 'stoplist.txt') # 2. 加载数据并处理类型警告 df = pd.read_csv('data.csv', dtype={'mixed_column': 'object'}) # 显式指定类型 # 3. jieba分词使用停止词 try: with open(stopwords_path, 'r', encoding='utf-8') as f: stopwords = set(f.read().splitlines()) except FileNotFoundError: print(f"错误:停止词文件 {stopwords_path} 未找到") text = "需要分词的文本" words = [word for word in jieba.cut(text) if word not in stopwords] ``` --- ### 相关问题 1. 如何动态获取Python脚本的当前工作目录? 2. pandas中如何批量处理多列的缺失值?[^3] 3. jieba分词支持哪些自定义词典加载方式? 4. 如何避免Python中的文件路径跨平台兼容性问题?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值