[转载] 使用Python在Pandas Dataframe中建立索引

参考链接: Python中NumPy的基本切片Slicing和高级索引Indexing

In Numpy arrays, we are familiar with the concepts of indexing, slicing, and masking, etc. Similarly, Pandas to supports indexing in their Dataframe. If we are familiar with the indexing in Numpy arrays, the indexing in Pandas will be very easy.

      在Numpy数组中,我们熟悉索引,切片和遮罩等概念。类似地,Pandas支持在其Dataframe中建立索引。 如果我们熟悉Numpy数组中的索引编制,那么Pandas中的索引编制将非常容易。  

     What is Indexing in Python?

      什么是Python中的索引编制?  

     Selecting values from particular rows and columns in a dataframe is known as Indexing. By using Indexing, we can select all rows and some columns or some rows and all columns.

      从数据框中的特定行和列中选择值称为索引。 通过使用索引,我们可以选择所有行和某些列,或者选择某些行和所有列。  

     Let’s create a sample data in a series form for better understanding of indexing.

      让我们以系列形式创建样本数据,以更好地理解索引。  

     

     The output series looks like this,

      输出系列看起来像这样,  

     1    a3    b5    cdtype: object

     Now, here Python offers two types of indices

      现在,这里Python提供了两种类型的索引  

     Explicit Explicit  Implicit Implicit  

     Explicit Indexing:

      明确索引:  

     For the above dataset if we pass the command as,

      对于上述数据集,如果我们将命令传递为  

     ds[1] it uses explicit indices

      ds[1]它使用显式索引  

     # If we pass the above command ds[1], the output will be'a'

     This is Explicit Indexing. Whereas, if we pass the command ds[1:3] it will use the implicit index style,

      这是显式索引。 而如果我们传递命令ds[1:3] ,它将使用隐式索引样式,  

     The output for the command ds[1:3] will be,

      命令ds[1:3]的输出为  

     3    b5    cdtype: object

     These slicing and indexing can lead to some sort of confusion. To avoid this, Python offers some special indexer attributes:

      这些切片和索引编制可能导致某种混乱。 为了避免这种情况,Python提供了一些特殊的indexer属性:  

     loc 位置 

     The loc attribute allows indexing and slicing that always references the explicit index

      loc属性允许始终引用显式索引的索引和切片  

     iloc iloc 

     The iloc attribute allows indexing and slicing that always references the implicit index style

      iloc属性允许始终引用隐式索引样式的索引和切片  

     One common expression in Python code that everyone follows and practices is “explicit is better than implicit.”

      每个人都遵循并实践的Python代码中的一个常见表达是“明确胜于隐含”。  

     Let’s take a sample dataset and see how indexing can be performed in different formats.

      让我们以一个样本数据集为例,看看如何以不同的格式执行索引。  

     We are using the data of NBA players from kaggle.

      我们正在使用kaggle提供的NBA球员数据。  

     

     The Dataset looks like this,

      数据集看起来像这样,  

    

   

   

    

     

      

       

        

         

          

           

            

           

          

         

        

       

       

        NBA Players sample dataset

       

       

         NBA球员样本数据集 

       

      

     

    

   

   

    

      单列 (Single Column) 

     To display a single column from the dataframe, we will mention the column name in the print statement.

      为了显示数据框中的单个列,我们将在print语句中提及列名。  

     

     The output will look like this,

      输出将如下所示:  

     

      

       

        

         

          

         

        

       

      

      

       Single Column from Dataset

      

      

        数据集中的单列 

      

     

      多列 (Multiple Columns) 

     Let’s try to display the ‘Age’, ‘College’ and ‘Draft Year’ of the players. We can display multiple columns in the following way,

      让我们尝试显示球员的“年龄”,“大学”和“起草年”。 我们可以通过以下方式显示多列,  

     

     The multiple columns will display like this,

      多列将显示如下,  

     

      

       

        

         

          

         

        

       

      

      

       Multiple Columns

      

      

        多列 

      

     

      .loc方法 (.loc Method) 

     Indexing using .loc method. If we use the .loc method, we have to pass the data using its Label name.

      使用.loc方法建立索引。 如果使用.loc方法,则必须使用其Label名称传递数据。  

      单排 (Single Row) 

     To display a single row from the dataframe, we will mention the row’s index name in the .loc method.

      为了显示数据框中的一行,我们将在.loc方法中提及该行的索引名称。  

     

     The whole row information will display like this,

      整行信息将像这样显示,  

     

      

       

        

         

          

         

        

       

      

      

       Single Row information

      

      

        单行信息 

      

     

      多行 (Multiple Rows) 

     Same as single row, pass the rows information in the print command to display the information.

      与单行相同,在print命令中传递行信息以显示信息。  

     

     The output will be,

      输出将是  

     

      

       

        

         

          

           

          

         

        

       

      

      

       Multiple Rows

      

      

        多行 

      

     

      选择行和列 (Selecting Rows and Columns) 

     We can also select multiple rows and multiple columns at a time using the .loc method.

      我们还可以使用.loc方法一次选择多个行和多个列。  

     

     The output will be like this,

      输出将是这样,  

     

      

       

        

         

          

         

        

       

      

      

       Displaying Rows and Columns

      

      

        显示行和列 

      

     

      所有行和某些列 (All Rows and Some Columns) 

     To display all the rows with some columns using the .loc method.

      使用.loc方法显示带有某些列的所有行。  

     

     The output of the above code will be like this,

      上面代码的输出将是这样,  

     

      

       

        

         

          

         

        

       

      

     

     The same output can be achieved by simply giving column names without using the .loc method as shown in Selecting Multiple Columns.

      只需提供列名而无需使用 选择多列中所示的 .loc 方法 ,就可以实现相同的输出。  

     

     The output will be same as the one above,

      输出将与上面的输出相同,  

     

      

       

        

         

          

         

        

       

      

      

       Same output without .loc

      

      

        没有.loc的相同输出 

      

     

      .iloc方法 (.iloc Method) 

     Indexing using the .iloc method. If we use the .iloc method, we have to pass the data using its Position. It is very similar to the .loc method, the only difference is .iloc uses integers to extract the information.

      使用.iloc方法建立索引。 如果使用.iloc方法,则必须使用其Position传递数据。 它与.loc方法非常相似,唯一的区别是.iloc使用整数来提取信息。  

      单排 (Single Row) 

     We have to pass a single integer in the .iloc method to get the row information.

      我们必须在.iloc方法中传递一个整数以获取行信息。  

     

     The output will be,

      输出将是  

     

      

       

        

         

          

         

        

       

      

      

       Single Row using .iloc method

      

      

        单行使用.iloc方法 

      

     

      多行 (Multiple Rows) 

     To select multiple rows, we have to pass the positions of the selected rows.

      要选择多行,我们必须传递所选行的位置。  

     

     The output will look something like this,

      输出看起来像这样,  

    

   

   

    

     

      

       

        

         

          

           

            

           

          

         

        

       

      

     

    

   

   

    

      选择行和列 (Selecting Rows and Columns) 

     To display a specific number of rows and columns, we create a list of integer for rows and a list of integer for columns and pass to iloc function.

      要显示特定数量的行和列,我们为行创建一个整数列表,为列创建一个整数列表,然后传递给iloc函数。  

     

     The output will be,

      输出将是  

     

      

       

        

         

          

         

        

       

      

      

       Rows and Columns iloc method

      

      

        行和列iloc方法 

      

     

      所有行和某些列 (All Rows and Some Columns) 

     To display all the rows, we have to pass “:” and the integers for columns.

      要显示所有行,我们必须传递“:”和列的整数。  

     

     The output will look like something like this,

      输出看起来像这样,  

     

      

       

        

         

          

         

        

       

      

      

       All Rows and Some columns iloc

      

      

        所有行和某些列iloc 

      

     

     If the columns in the dataset are of “int” or “float” type, then we can apply all the numeric operations to the column directly and manipulate the data to our requirements.

      如果数据集中的列为“ int”或“ float”类型,则我们可以将所有数值运算直接应用于该列,并根据需要操作数据。  

      使用.loc方法的数值运算 (Numeric Operations using .loc method) 

     

     The output will be like this,

      输出将是这样,  

     

      

       

        

         

          

         

        

       

      

      

       Numeric operations using loc function

      

      

        使用loc函数进行数值运算 

      

     

      使用.iloc方法的数值运算 (Numeric operations using .iloc Method) 

     

     The output will be same as the previous one with .loc method

      输出将与使用.loc方法的上一个输出相同  

     

      

       

        

         

          

         

        

       

      

     

      结论 (Conclusion) 

     We can conclude this article in three simple statements.

      我们可以用三个简单的语句来结束本文。  

     To avoid confusion on Explicit Indices and Implicit Indices we use .loc and .iloc methods. 为避免对显式索引和隐式索引造成混淆,我们使用.loc和.iloc方法。 .loc method is used for label based indexing. .loc方法用于基于标签的索引。 .iloc method is used for position based indexing. .iloc方法用于基于位置的索引。 

     These are the three main statements, we need to be aware of while using indexing methods for a Pandas Dataframe in Python.

      这是三个主要语句,我们在使用Python中的Pandas Dataframe的索引方法时需要注意。  

     Thank you for reading and Happy Coding!!!

      感谢您的阅读和快乐编码!!!  

      在这里查看我以前关于Python的文章 (Check out my previous articles about Python here) 

     Seaborn: Python Seaborn:Python Pandas: Python 熊猫:Python Matplotlib: Python Matplotlib:Python NumPy: Python NumPy:Python Data Visualization and its Importance: Python 数据可视化及其重要性:Python Time Complexity and Its Importance in Python 时间复杂度及其在Python中的重要性 Python Recursion or Recursive Function in Python Python中的Python递归或递归函数 

    

   

  

 

 

  翻译自: https://towardsdatascience.com/indexing-in-pandas-dataframe-using-python-63dcc6242323

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用以下代码建立一个空的DataFrame: ```python import pandas as pd df = pd.DataFrame() ``` 这个DataFrame没有任何行或列,但是你可以通过添加行或列来填充它。 ### 回答2: PandasPython一种基于Numpy的数据处理库,它提供了丰富的数据结构和数据分析工具,包括Series、DataFrame和Panel等。其最常用的是DataFrame,它类似于一张表格,可以方便地对数据进行操作和分析。 在使用Pandas时,有时会需要先创建一个空的DataFrame,用于后续数据的填充和操作。建立空的DataFrame很简单,只需要使用pd.DataFrame()函数,并不传入任何参数即可。示例代码如下: import pandas as pd df = pd.DataFrame() 可以看到,我们先导入了Pandas库,并创建了一个名为df的DataFrame。在创建DataFrame时,并未传入任何参数,因此它是一个空的DataFrame。 与正常的DataFrame一样,我们也可以对其进行操作,比如新增一列数据: df['Name'] = ['Alice', 'Bob', 'Charlie'] 新增一列数据的方式很简单,只需要使用DataFrame的列索引,并赋值即可。可以看到,在新增一列数据后,DataFrame变成了下面这样: Name 0 Alice 1 Bob 2 Charlie 此时,我们再新增一列数据: df['Age'] = [20, 25, 30] 同样地,我们使用DataFrame的列索引,并赋值新增一列数据。此时,DataFrame变成了下面这样: Name Age 0 Alice 20 1 Bob 25 2 Charlie 30 以上就是Pandas建立DataFrame的方法,通过pd.DataFrame()函数,不传入任何参数即可创建一个空的DataFrame。之后,我们就可以对其进行操作,比如新增一列数据等,方便地对数据进行处理和分析。 ### 回答3: pandas是一个Python库,用于数据处理和分析,特别是适用于处理结构化、标记化数据。在pandas,要创建一个空dataframe可以按照以下方式进行操作: 首先,导入pandas库: ``` import pandas as pd ``` 接着使用pandas.DataFrame()函数来创建一个空的dataframe: ``` df = pd.DataFrame() ``` 在这里,我们声明了一个变量df作为我们要创建的空dataframe。通过调用pd.DataFrame()函数并不带任何参数来创建一个空的dataframe。这将生成一个没有任何行和列的空dataframe。 我们可以使用print函数来打印生成的空dataframe: ``` print(df) ``` 执行上面代码,输出如下: ``` Empty DataFrame Columns: [] Index: [] ``` 从上面的输出可以看出,我们已经成功地创建了一个空的dataframe,并且它现在不包含任何行和列。 这样创建的dataframe可以方便后续进行添加表头和数据等操作。在实际的数据处理,通常需要定义列名和数据类型,然后再添加行和数据。我们可以通过以下操作来定义列名和数据类型: ``` df = pd.DataFrame(columns=['列1','列2','列3'], dtype=int) ``` 在这里,我们传递了一个名为“columns”的参数,该参数包含要为dataframe定义的列名。我们还为“dtype”参数指定了整数数据类型。这将生成一个包含三列的dataframe,列名分别为“列1”,“列2”和“列3”,每列的数据类型都为整数。类似地,我们可以根据需要定义其他数据类型和列名。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值