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!

댓글

이 블로그의 인기 게시물

Tomcat(톰캣) SSL 포트 설정

How to split a list into chunks of 100 items in JavaScript, 자바스크립트 리스트 쪼개기

How to catch exceptions on Future in Java, 자바 Future 에러 잡기

Using the MinIO API via curl

운영체제를 개발 방법

dagrun_timeout of Airflow

What are 5 creative things I could do with my kids' art, 아이와 함께하는 창의적 놀이

In HBase, the "memory to disk" flush operation

[OS_Linux_Ubuntu] telnet & ssh 설치와 설정 (installation / configuration)

[Ubuntu] *.deb 파일 설치 방법