python中的dataframe 剔除部分数据后,索引消失,重新建立索引

今天在处理一个数据的过程中出现问题,python中的dataframe 剔除部分数据后,索引消失,遍历就出错,

报错形式如下

Traceback (most recent call last):
  File "D:/pycreate/tianchi_糖尿病/data_pre/split_data.py", line 53, in <module>
    handler_data()
  File "D:/pycreate/tianchi_糖尿病/data_pre/split_data.py", line 32, in handler_data
    print(indexdf["S"][i])
  File "D:\ANACONDA\ana3.5.2\lib\site-packages\pandas\core\series.py", line 766, in __getitem__
    result = self.index.get_value(self, key)
  File "D:\ANACONDA\ana3.5.2\lib\site-packages\pandas\core\indexes\base.py", line 3103, in get_value
    tz=getattr(series.dtype, 'tz', None))
  File "pandas\_libs\index.pyx", line 106, in pandas._libs.index.IndexEngine.get_value
  File "pandas\_libs\index.pyx", line 114, in pandas._libs.index.IndexEngine.get_value
  File "pandas\_libs\index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 958, in pandas._libs.hashtable.Int64HashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 964, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 31

后来找了以下是由于我对原始数据删除了部分异常数据导致的,。

#会导致原索引丢失,30-32
    indexdf=indexdf[indexdf["EE"]!=0]

解决方案

   #重新定义索引,才能支持遍历
    # indexdf = indexdf.reset_index(drop=True)

代码:

  indexdf=pd.read_table("0.ann",sep="\s+",names=["T","TC","S","E","name"])
  indexdf["EE"] = indexdf["E"].apply(lambda x: x if ";" not in x else 0)
  indexdf=indexdf[indexdf["EE"]!=0]
        #重新定义索引,才能支持遍历
 indexdf = indexdf.reset_index(drop=True)
 for i in range(len(indexdf)):
    
            print(indexdf["S"][i])

pandas 使用apply 处理多列数据

直接上代码

import pandas as pd
def my_min(a, b):
    return min(abs(a),abs(b)


s = pd.Series([10.0247,10.0470, 10.0647,10.0761,15.0800,10.0761,10.0647,10.0470,10.0247,10.0,9.9753,9.9530,9.9353,9.9239,18.92,9.9239,9.9353,9.9530,9.9753,10.0])
df = pd.DataFrame(s)
df.columns=['value']
df['val_1'] = df['value'].diff()
df['val_2'] = df['val_1'].shift(-1)
df['val'] = df.apply(lambda row: my_min(row['val_1'], row['val_2']), axis=1)

欢迎加入Python快速进阶QQ群:867300100

微信号
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT界的小小小学生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值