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!

댓글

이 블로그의 인기 게시물

Delete topic on Kafka, 카프카 토픽 삭제하기

ftplib.error_perm: 550 Permission denied

JAVA 실행 스크립트

how to delete all issues on project in sentry, 센트리 이슈 삭제하기

Offset out of range error in Kafka, 카프카 트러블슈팅

Reactjs datetime range picker

Pyspark 를 사용한 테이블 조인, table join with pyspark

Create fixed rounded button by Tailwind

To change the ESE index in Fluent Bit

To create a drawer in the footer using Tailwind CSS