[파이썬] pandas 인덱서 (at, iat, xs)

Pandas is a powerful Python library widely used for data manipulation and analysis. One of the key features of Pandas is its flexible indexing capabilities, which allow users to access and modify data in a variety of ways. In this blog post, we will explore three important indexing methods in Pandas: at, iat, and xs.

at indexer

The at indexer allows you to access a single value in a DataFrame or Series by specifying the row and column labels. It is faster than the traditional loc indexer when you only need to retrieve or set a single value.

Here is an example of using the at indexer:

import pandas as pd

data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)

value = df.at[0, 'A']  # Access the value at row 0, column 'A'
print(value)  # Output: 1

df.at[1, 'B'] = 10  # Set the value at row 1, column 'B' to 10
print(df)

# Output:
#    A   B
# 0  1   4
# 1  2  10
# 2  3   6

iat indexer

Similar to at, the iat indexer allows you to access a single value by specifying the row and column integer positions. It provides a faster way to access a single value in a DataFrame or Series.

Here is an example of using the iat indexer:

import pandas as pd

data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)

value = df.iat[0, 1]  # Access the value at row 0, column 1
print(value)  # Output: 4

df.iat[1, 0] = 100  # Set the value at row 1, column 0 to 100
print(df)

# Output:
#     A  B
# 0   1  4
# 1  100  5
# 2   3  6

xs indexer

The xs indexer stands for “cross-section” and allows you to select a specific row or column from a multi-level indexed DataFrame. It is particularly useful when dealing with hierarchical data structures.

Here is an example of using the xs indexer:

import pandas as pd

data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
index = pd.MultiIndex.from_tuples([('X', 'a'), ('X', 'b'), ('Y', 'c')], names=['Label1', 'Label2'])
df = pd.DataFrame(data, columns=['A', 'B'], index=index)

row = df.xs('X', level='Label1')  # Select all rows with 'X' in the first level of the index
print(row)

# Output:
#         A  B
# Label2      
# a       1  4
# b       2  5

column = df.xs('B', axis=1, level='Label2')  # Select the 'B' column from the second level of the index
print(column)

# Output:
# Label1
# X    4
# Y    6

In this example, we have a DataFrame with a multi-level index. By using the xs indexer, we can select specific rows or columns based on the values in different levels of the index.

These indexing methods in Pandas provide powerful and efficient ways to access and modify data in DataFrames and Series. Understanding and utilizing them can greatly enhance your data manipulation workflow.