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))
]

### Pandas多重索引使用方法 多重索引(MultiIndex)是Pandas中一种强大的数据结构,允许在DataFrame或Series对象中同时使用多个层级的索引。以下是对多重索引的详细说明和使用方法。 #### 1. 构建多重索引 多重索引可以通过多种方式构建。例如,可以使用`MultiIndex.from_tuples()`方法从元组列表创建索引[^1]: ```python import pandas as pd tuples = [('A', 'a'), ('B', 'b')] index = pd.MultiIndex.from_tuples(tuples, names=['row1', 'row2']) print(index) ``` 此外,还可以通过`MultiIndex.from_product()`方法构建多重索引[^2]。这种方法适用于需要生成所有可能组合的情况: ```python levels = [['A', 'B'], ['a', 'b']] index = pd.MultiIndex.from_product(levels, names=['row1', 'row2']) print(index) ``` #### 2. 创建带有多重索引的DataFrame 一旦构建了多重索引,可以将其赋值给DataFrame的索引或列。例如: ```python data = [[1, 2], [3, 4]] df = pd.DataFrame(data, columns=['col1', 'col2'], index=index) print(df) ``` #### 3. 访问和操作多重索引 多重索引支持多种访问方式。例如,可以通过`.xs()`方法选择特定层级的数据[^3]: ```python # 选择row1为'A'的所有行 result = df.xs('A', level='row1') print(result) ``` 也可以通过`.loc[]`直接指定索引层级进行访问: ```python # 选择row1为'A'且row2为'a'的行 result = df.loc[('A', 'a')] print(result) ``` #### 4. 补全子索引缺失 如果某些子索引缺失,可以使用`reindex()`方法补全[^1]。例如: ```python new_index = pd.MultiIndex.from_product([['A', 'B', 'C'], ['a', 'b']], names=['row1', 'row2']) df_reindexed = df.reindex(new_index, fill_value=0) print(df_reindexed) ``` #### 5. 转换和重塑 多重索引支持多种转换和重塑操作。例如,可以使用`.stack()`和`.unstack()`方法在行和列之间切换索引层级: ```python # 将列索引转换为行索引 result = df.stack() print(result) # 将行索引转换为列索引 result = df.unstack() print(result) ``` ### 注意事项 - 在构建多重索引时,确保各层级的索引名称唯一,以避免混淆。 - 使用`.xs()`方法时,注意指定正确的层级名称或位置。 - 补全缺失索引时,需明确指定填充值(如`fill_value`参数)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值