pandas二、索引、选择以及赋值

本文通过Python的pandas库,对葡萄酒评论数据集进行了一系列的数据探索操作,包括读取CSV文件、查看数据头、选取特定列、获取单行记录、选择前几行描述、按索引选取特定行以及创建包含特定列的子数据集。

首先是检查是否数据

import pandas as pd
reviews = pd.read_csv("winemag-data-130k-v2.csv", index_col=0)
reviews.head()
 countrydescriptiondesignationpointspriceprovinceregion_1region_2taster_nametaster_twitter_handletitlevarietywinery
0ItalyAromas include tropical fruit, broom, brimston...Vulkà Bianco87NaNSicily & SardiniaEtnaNaNKerin O’Keefe@kerinokeefeNicosia 2013 Vulkà Bianco (Etna)White BlendNicosia
1PortugalThis is ripe and fruity, a wine that is smooth...Avidagos8715.0DouroNaNNaNRoger Voss@vossrogerQuinta dos Avidagos 2011 Avidagos Red (Douro)Portuguese RedQuinta dos Avidagos
2USTart and snappy, the flavors of lime flesh and...NaN8714.0OregonWillamette ValleyWillamette ValleyPaul Gregutt@paulgwineRainstorm 2013 Pinot Gris (Willamette Valley)Pinot GrisRainstorm
3USPineapple rind, lemon pith and orange blossom ...Reserve Late Harvest8713.0MichiganLake Michigan ShoreNaNAlexander PeartreeNaNSt. Julian 2013 Reserve Late Harvest Riesling ...RieslingSt. Julian
4USMuch like the regular bottling from 2012, this...Vintner's Reserve Wild Child Block8765.0OregonWillamette ValleyWillamette ValleyPaul Gregutt@paulgwineSweet Cheeks 2012 Vintner's Reserve Wild Child...Pinot NoirSweet Cheeks

           1、 从结果中选择某一列 进行赋值

desc = reviews.description
# or
desc = reviews["description"]  # 这两个都可以
desc.head()
"""
0    Aromas include tropical fruit, broom, brimston...
1    This is ripe and fruity, a wine that is smooth...
2    Tart and snappy, the flavors of lime flesh and...
3    Pineapple rind, lemon pith and orange blossom ...
4    Much like the regular bottling from 2012, this...
Name: description, dtype: object
"""

   2、从reviws的description列取第一个值 

first_description = reviews.description.iloc[0]
first_description
'''
"Aromas include tropical fruit, broom, brimstone and dried herb. The palate isn't overly expressive, offering unripened apple, citrus and dried sage alongside brisk acidity."
'''

  3、取第一行的值,即第一行记录

first_row = reviews.iloc[0]
first_row
'''
country                                                              Italy
description              Aromas include tropical fruit, broom, brimston...
designation                                                   Vulkà Bianco
points                                                                  87
price                                                                  NaN
province                                                 Sicily & Sardinia
region_1                                                              Etna
region_2                                                               NaN
taster_name                                                  Kerin O’Keefe
taster_twitter_handle                                         @kerinokeefe
title                                    Nicosia 2013 Vulkà Bianco  (Etna)
variety                                                        White Blend
winery                                                             Nicosia
Name: 0, dtype: object
'''

      4、选取reviews中description列的前10行值。

first_description = reviews.description.iloc[:10]
first_description
'''
0    Aromas include tropical fruit, broom, brimston...
1    This is ripe and fruity, a wine that is smooth...
2    Tart and snappy, the flavors of lime flesh and...
3    Pineapple rind, lemon pith and orange blossom ...
4    Much like the regular bottling from 2012, this...
5    Blackberry and raspberry aromas show a typical...
6    Here's a bright, informal red that opens with ...
7    This dry and restrained wine offers spice in p...
8    Savory dried thyme notes accent sunnier flavor...
9    This has great depth of flavor with its fresh ...
Name: description, dtype: object
'''

   5、选取索引1,2,3,5,8的记录行 

index = [1,2,3,5,8]
sample_reviews = reviews.iloc[index]
# sample_reviews = reviews.loc[index]
'''
这里loc 和 iloc的区别是:
iloc:
      是你选择的是第1,2,3,5,8行
而loc:
      则是根据你的索引 比如你的索引是从1500开始往后递增的 那么用上面的1,2,3,5,8就会报错
      应该用[1501,1502,1503,1505,1508]
'''
# result

        6、创建一个变量df,df包含reviews的 `country`, `province`, `region_1`, and `region_2`列,并保留索引 0 1 10 100的记录,换言之产生一个如下的DataFrame: 

                                              

cols = ['country', 'province', 'region_1', 'region_2']
indices = [0, 1, 10, 100]
reviews.loc[indices, cols]
# 运行结果如下:
 countryprovinceregion_1region_2
0ItalySicily & SardiniaEtnaNaN
1PortugalDouroNaNNaN
10USCaliforniaNapa ValleyNapa
100USNew YorkFinger LakesFinger Lakes

        7、 创建包含country、variety列且保留前100行数据的变量df:

cols = ['country', 'variety']
df = reviews.loc[:99, cols]
# or

cols_idx = [0, 11]
df = reviews.iloc[:100, cols_idx]
 countryvariety
0ItalyWhite Blend
1PortugalPortuguese Red
2USPinot Gris
3USRiesling
4USPinot Noir
5Spain

Tempranillo-Merlot

                 .........................................................................
       8、创建一个DataFrame 名字叫做italian_wines,包含 ‘Italy’列 即 酒的产地。提示: `reviews.country`

italian_wines = reviews[reviews.country == 'Italy']
italian_wines.head()

9、创建一个DataFrame名字叫做top_oceania_wines,包含至少95行以上产地来自Australia或new zealand的信息。

top_oc = reviews[
    (reviews.country.isin(['Australia','new zealand'])&(reviews.points >= 95))
]

<think>根据用户问题,用户想了解Pandas如何设置索引。结合引用内容,特别是引用[1]中提到索引设置和重新设置索引的函数,引用[2][3]提到多层索引索引)的操作,可以总结设置索引的方法。 1. 使用`set_index`方法:将现有列转换为索引,可以同时选择多列来创建索引。 2. 使用`MultiIndex`对象:直接创建多层索引,然后赋值给DataFrame的index或columns属性。 具体步骤: - 方法一:使用`set_index`方法,传入两个列名(列表形式),即可将这两列设置为索引。 - 方法:使用`pd.MultiIndex`创建多层索引,再赋值给DataFrame的index。 此外,引用[2]中提到`pd.IndexSlice`用于多层索引的切片,但设置索引主要使用上述两种方法。 下面给出示例代码: </think> ### Pandas设置索引的方法 在Pandas中设置索引(多层索引)主要有以下两种方法: #### 方法1:使用`set_index()`方法(推荐) 这是最常用的方式,可将现有的DataFrame列转换为索引: ```python import pandas as pd # 创建示例DataFrame data = { '城市': ['北京', '北京', '上海', '上海', '广州'], '区域': ['朝阳', '海淀', '浦东', '徐汇', '天河'], '销售额': [250, 180, 300, 220, 150] } df = pd.DataFrame(data) # 设置索引(城市+区域) df_multi = df.set_index(['城市', '区域']) print(df_multi) ``` 输出结果: ``` 销售额 城市 区域 北京 朝阳 250 海淀 180 上海 浦东 300 徐汇 220 广州 天河 150 ``` #### 方法2:使用`MultiIndex`对象 直接创建多层索引对象后赋值: ```python # 创建索引对象 new_index = pd.MultiIndex.from_arrays( [['北京', '北京', '上海', '上海', '广州'], ['朝阳', '海淀', '浦东', '徐汇', '天河']], names=('城市', '区域') ) # 应用新索引 df.index = new_index print(df.drop(columns=['城市', '区域'])) # 移除原始列 ``` ### 关键说明 1. **索引优势**:多层索引可显著提升查询效率: - 当索引唯一时:哈希表优化($O(1)$)[^1] - 索引有序时:分查找($O(logN)$)[^1] 2. **索引操作**: - 重置索引:`df.reset_index()` - 交叉切片:使用`pd.IndexSlice`进行高级查询[^2] ```python idx = pd.IndexSlice df_multi.loc[idx['北京', :]] # 获取北京所有区域数据 ``` 3. **注意事项**: - 设置索引后原列会被移除,需提前备份 - 使用`sort_index()`提升查询性能 - 分组操作自动生成多级索引[^3]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值