To get a row from a pandas.core.frame.DataFrame in Python

To get a row from a pandas.core.frame.DataFrame in Python, you can use several methods depending on how you want to access the row. Here's how you can do it:

1. Access by Index

Use iloc or loc:

  • iloc: Access by integer-based position (row number).
  • loc: Access by label-based index.
import pandas as pd

# Sample DataFrame
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
df = pd.DataFrame(data)

# Access the first row (integer index)
row1 = df.iloc[0]
print(row1)

# Access a row by index label (if set)
row_by_label = df.loc[0]  # Assuming index is not customized
print(row_by_label)

2. Access Rows Based on Conditions

You can filter rows based on a condition:

# Get rows where column 'A' equals 2
filtered_row = df[df['A'] == 2]
print(filtered_row)

3. Access Rows Using Slicing

For multiple rows, use slicing with iloc or loc:

# Get the first two rows
rows = df.iloc[:2]
print(rows)

# Get rows with index labels from 0 to 1 (inclusive)
rows_with_labels = df.loc[0:1]
print(rows_with_labels)

4. Access as a Dictionary or Array

If you need the row as a dictionary or array:

# Convert row to a dictionary
row_dict = df.iloc[0].to_dict()
print(row_dict)

# Convert row to a NumPy array
row_array = df.iloc[0].to_numpy()
print(row_array)

Notes:

  • iloc is zero-based, while loc is label-based.
  • If the DataFrame index is not numeric or customized, use loc with the correct index label.

Let me know if you need further clarification!

댓글

이 블로그의 인기 게시물

To switch to a specific tag in a Git repository

How to checkout branch of remote git, 깃 리모트 브랜치 체크아웃

Using the MinIO API via curl

To download a file from MinIO using Spring Boot, 스프링부트 Minio 사용하기

리눅스의 부팅과정 (프로세스, 서비스 관리)

Chromium 개발 환경 세팅, 크로미움 개발 준비하기

Joining an additional control plane node to an existing Kubernetes cluster

urllib3 with proxy settings

CDPEvents in puppeteer

Avro + Grpc in python