数据分析-day06-pandas-dataFrame的set_index 详解

本文详细介绍了Pandas中set_index方法的使用,包括如何通过该方法设置单索引和复合索引,以及如何保留或删除原来的列作为新索引。同时,探讨了inplace参数的作用,展示了设置索引后的数据变化。
DataFrame可以通过set_index方法,可以设置单索引和复合索引。
set_index( ) 将 DataFrame 中的列转化为行索引。默认的,当列变成行索引之后,原来的列就没了,但是可以通过设置drop来保留原来的列。
 DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)
append添加新索引,
drop:默认为true,表示是否删除列作为新索引。
inplace:false 原数据对象不改变,新创建一个包含修改内容的对象;True:在源对象上修改内容,不创建一个新对象
# -*- coding: utf-8 -*-

# @File    : test.py
# @Date    :  2020-01-06 22:15
# @Author  : admin
import pandas as pd
# DataFrame可以通过set_index方法,可以设置单索引和复合索引。
#set_index( ) 将 DataFrame 中的列转化为行索引。默认的,当列变成行索引之后,原来的列就没了,但是可以通过设置drop来保留原来的列。
# DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)
# append添加新索引,
#drop:默认为true,表示是否删除列作为新索引。
#inplace:false 原数据对象不改变,新创建一个包含修改内容的对象;True:在源对象上修改内容,不创建一个新对象
df = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3', 'A4'],
                   'B': ['B0', 'B1', 'B2', 'B3', 'B4'],
                   'C': ['C0', 'C1', 'C2', 'C3', 'C4'],
                   'D': ['D0', 'D1', 'D2', 'D3', 'D4']})
print('----------------------------------------inpla默认为False -------------------------')
print("##############################原数据df:\n",df)
df_inplace_f = df.set_index('A', inplace=False)  # inpla默认为False,表示适当修改DataFrame(不要创建新对象)
print('设置索引后df:\n', df)
print('设置索引新对象df_inplace_f:\n', df_inplace_f)    #原数据对象不改变,新创建一个对象

print('----------------------------------------inpla默认为True==========================================')

df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3', 'A4'],
                    'B': ['B0', 'B1', 'B2', 'B3', 'B4'],
                    'C': ['C0', 'C1', 'C2', 'C3', 'C4'],
                    'D': ['D0', 'D1', 'D2', 'D3', 'D4']})
print("==================================================原df1:\n",df1)
df_inplace_t = df1.set_index('A', inplace=True)  # 表示原地不动
print("==================================================设置索引后df1:\n",df1)
print("========================================================设置索引df_inplace_t:",df_inplace_t)

----------------------------------------inpla默认为False -------------------------
##############################原数据df:
     A   B   C   D
0  A0  B0  C0  D0
1  A1  B1  C1  D1
2  A2  B2  C2  D2
3  A3  B3  C3  D3
4  A4  B4  C4  D4
设置索引后df:
     A   B   C   D
0  A0  B0  C0  D0
1  A1  B1  C1  D1
2  A2  B2  C2  D2
3  A3  B3  C3  D3
4  A4  B4  C4  D4
设置索引新对象df_inplace_f:
      B   C   D
A             
A0  B0  C0  D0
A1  B1  C1  D1
A2  B2  C2  D2
A3  B3  C3  D3
A4  B4  C4  D4
----------------------------------------inpla默认为True==========================================
==================================================原df1:
     A   B   C   D
0  A0  B0  C0  D0
1  A1  B1  C1  D1
2  A2  B2  C2  D2
3  A3  B3  C3  D3
4  A4  B4  C4  D4
==================================================设置索引后df1:
      B   C   D
A             
A0  B0  C0  D0
A1  B1  C1  D1
A2  B2  C2  D2
A3  B3  C3  D3
A4  B4  C4  D4
========================================================设置索引df_inplace_t: None

--------------------------------------------------------------------------- KeyError Traceback (most recent call last) File ~\anaconda3\Lib\site-packages\pandas\core\indexes\base.py:3791, in Index.get_loc(self, key) 3790 try: -> 3791 return self._engine.get_loc(casted_key) 3792 except KeyError as err: File index.pyx:152, in pandas._libs.index.IndexEngine.get_loc() File index.pyx:181, in pandas._libs.index.IndexEngine.get_loc() File pandas\_libs\hashtable_class_helper.pxi:7080, in pandas._libs.hashtable.PyObjectHashTable.get_item() File pandas\_libs\hashtable_class_helper.pxi:7088, in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: 'date' The above exception was the direct cause of the following exception: KeyError Traceback (most recent call last) Cell In[5], line 409 406 print("训练流程完成!") 408 if __name__ == "__main__": --> 409 main() Cell In[5], line 326, in main() 323 positive_samples['label'] = 1 325 # 负样本采样 --> 326 negative_samples = vectorized_negative_sampling( 327 hist_exposure, positive_samples, sample_ratio=0.05 328 ) 330 # 合并数据集 331 click_data = pd.concat([positive_samples, negative_samples], ignore_index=True) Cell In[5], line 130, in vectorized_negative_sampling(exposure, positive_set, sample_ratio) 127 negative_samples['label'] = 0 129 # 添加时间信息(使用最近曝光时间) --> 130 negative_samples['date'] = exposure['date'].max() 132 return negative_samples File ~\anaconda3\Lib\site-packages\pandas\core\frame.py:3893, in DataFrame.__getitem__(self, key) 3891 if self.columns.nlevels > 1: 3892 return self._getitem_multilevel(key) -> 3893 indexer = self.columns.get_loc(key) 3894 if is_integer(indexer): 3895 indexer = [indexer] File ~\anaconda3\Lib\site-packages\pandas\core\indexes\base.py:3798, in Index.get_loc(self, key) 3793 if isinstance(casted_key, slice) or ( 3794 isinstance(casted_key, abc.Iterable) 3795 and any(isinstance(x, slice) for x in casted_key) 3796 ): 3797 raise InvalidIndexError(key) -> 3798 raise KeyError(key) from err 3799 except TypeError: 3800 # If we have a listlike key, _check_indexing_error will raise 3801 # InvalidIndexError. Otherwise we fall through and re-raise 3802 # the TypeError. 3803 self._check_indexing_error(key) KeyError: 'date'
07-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值