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!

댓글

이 블로그의 인기 게시물

Sparse encoder

To build a gRPC service with Gradle, Java, and Avro

Using venv in Python

how to delete doc of datastream in elasticsearch, 엘라스틱서치 데이터스트림 도규먼트 삭제하기

Typescript interface, 타입스크립트 인터페이스

Read a file in Java, 자바 파일 읽기

kubernetes cronjob logs

max_active_runs of Airflow

configure telnet server, 텔넷 서버 설정하기

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