本文共 3223 字,大约阅读时间需要 10 分钟。
Pandas DataFrame index and columns attributes allow us to get the rows and columns label values.
Pandas DataFrame的索引和列属性允许我们获取行和列的标签值。
We can pass the integer-based value, , or arguments to get the label information.
我们可以传递基于整数的value, 或参数来获取标签信息。
Let’s look into some examples of getting the labels of different rows in a DataFrame object. Before we look into the index attribute usage, we will create a sample DataFrame object.
让我们看一些获取DataFrame对象中不同行的标签的示例。 在研究索引属性的用法之前,我们将创建一个示例DataFrame对象。
import pandas as pdd1 = {'Name': ['John', 'Jane', 'Mary'], 'ID': [1, 2, 3], 'Role': ['CEO', 'CTO', 'CFO']}df = pd.DataFrame(d1, index=['A', 'B', 'C'])print('DataFrame:\n', df)
Output:
输出:
DataFrame: Name ID RoleA John 1 CEOB Jane 2 CTOC Mary 3 CFO
row_1_label = df.index[1]print(type(row_1_label)) #print(row_1_label) # B
rows_labels = df.index[[1, 2]]print(type(rows_labels)) #print(rows_labels) # Index(['B', 'C'], dtype='object')
rows_labels = df.index[1:3]print(type(rows_labels)) #print(rows_labels) # Index(['B', 'C'], dtype='object')
rows_labels = df.index[[True, False, True]]print(type(rows_labels)) #print(rows_labels) # Index(['A', 'C'], dtype='object')
We can’t set the rows label value using the DataFrame index attribute. If we try to do that, it will raise TypeError(“Index does not support mutable operations”).
我们无法使用DataFrame index属性设置行标签值。 如果我们尝试这样做,它将引发TypeError(“ Index不支持可变操作”) 。
df.index[0] = 'a' # TypeError: Index does not support mutable operations
The DataFrame columns attribute provides the label values for columns. It’s very similar to the index attribute. We can’t set the columns label value using this attribute. Let’s look at some examples of using the DataFrame columns attribute. We will reuse the earlier defined DataFrame object for these examples.
DataFrame列属性提供列的标签值。 它与index属性非常相似。 我们无法使用此属性设置列标签值。 让我们看一些使用DataFrame columns属性的示例。 对于这些示例,我们将重用先前定义的DataFrame对象。
column_1_label = df.columns[1]print(type(column_1_label)) #print(column_1_label) # ID
columns_labels = df.columns[[1, 2]]print(type(columns_labels)) #print(columns_labels) # Index(['ID', 'Role'], dtype='object')
columns_labels = df.columns[1:3]print(columns_labels) # Index(['ID', 'Role'], dtype='object')
columns_labels = df.columns[[False, False, True]]print(columns_labels) # Index(['Role'], dtype='object')
Pandas DataFrame index and columns attributes are helpful when we want to process only specific rows or columns. It’s also useful to get the label information and print it for future debugging purposes.
当我们只想处理特定的行或列时,Pandas DataFrame的索引和列属性很有用。 获取标签信息并打印以供将来调试时也很有用。
翻译自:
转载地址:http://wymzd.baihongyu.com/