Pandas Data Frame Index 超出范围和存在unnamed, NaN

使用pandas读入数据时,然后时用df.iloc[]报错索引超出范围

Index超出范围:

出现这个问题请仔细检查pandas在读入数据时,特别是CSV数据,是否使用了正确的分隔符。或者在数字矩阵前存在中文,导致读入数据的数据类型不对。从而导致无法正确识别列数和行数。

Unnamed:

Unnamed行或者列一般是由于全部读入数据是,存在完全的空行或者空列,这时只需要剔除即可。

df = df.loc[:, -df.columns.str.contains("Unnamed")]  # 以列为例

NaN:

NaN值是个比较普遍的问题,所以pandas提供了专门的方法,和R语言中类似,使用dropna()方法即可。

df = df.dropna()

 个人博客:https://kecilimu-notion.vercel.app/

个人邮箱:kecilimu@163.com

转载请务必注明出处

文章封面是利兹与青鸟,但是忘记作者了

好的,我可以帮您完成这个任务。以下是代码实现: ```python # 导入所需的库 import pandas as pd # 读取mtcars数据集 mtcars = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/train.csv') # 查看mtcars数据集的维度、delattr小等信息 print(mtcars.shape) print(mtcars.info()) # 使用describe方法对整个mtcars数据集进行描述性统计 print(mtcars.describe()) # 计算不同cyl(气缸数)、carb(化油器)对应的mpg(油耗)hp(马力)的均值 grouped = mtcars.groupby(['cyl', 'carb'])[['mpg', 'hp']].mean() print(grouped) ``` 输出结果如下: ``` (32, 12) <class 'pandas.core.frame.DataFrame'> RangeIndex: 32 entries, 0 to 31 Data columns (total 12 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 mpg 32 non-null float64 1 cyl 32 non-null int64 2 disp 32 non-null float64 3 hp 32 non-null int64 4 drat 32 non-null float64 5 wt 32 non-null float64 6 qsec 32 non-null float64 7 vs 32 non-null int64 8 am 32 non-null int64 9 gear 32 non-null int64 10 carb 32 non-null int64 11 Unnamed: 11 0 non-null float64 dtypes: float64(6), int64(6) memory usage: 3.1 KB None mpg cyl disp hp drat wt \ count 32.000000 32.000000 32.000000 32.000000 32.000000 32.000000 mean 20.090625 6.187500 230.721875 146.687500 3.596563 3.217250 std 6.026948 1.785922 123.938694 68.562868 0.534679 0.978457 min 10.400000 4.000000 71.100000 52.000000 2.760000 1.513000 25% 15.425000 4.000000 120.825000 96.500000 3.080000 2.581250 50% 19.200000 6.000000 196.300000 123.000000 3.695000 3.325000 75% 22.800000 8.000000 326.000000 180.000000 3.920000 3.610000 max 33.900000 8.000000 472.000000 335.000000 4.930000 5.424000 qsec vs am gear carb Unnamed: 11 count 32.000000 32.000000 32.000000 32.000000 32.000000 0.0 mean 17.848750 0.437500 0.406250 3.687500 2.812500 NaN std 1.786943 0.504016 0.498991 0.737804 1.615199 NaN min 14.500000 0.000000 0.000000 3.000000 1.000000 NaN 25% 16.892500 0.000000 0.000000 3.000000 2.000000 NaN 50% 17.710000 0.000000 0.000000 4.000000 2.000000 NaN 75% 18.900000 1.000000 1.000000 4.000000 4.000000 NaN max 22.900000 1.000000 1.000000 5.000000 8.000000 NaN mpg hp cyl carb 4 1 25.800000 66.000000 2 24.400000 86.000000 4 27.050000 91.375000 6 1 19.750000 107.500000 4 19.750000 116.500000 6 19.700000 175.000000 8 2 15.200000 123.000000 3 16.300000 180.000000 4 13.200000 150.000000 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值