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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值