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!

댓글

이 블로그의 인기 게시물

Boilerplate for typescript server programing

Gradle multi-module project

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

Using the MinIO API via curl

HTML Inline divisions at one row by Tailwind

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

Declaration of custom object or type in Node.js

CDPEvents in puppeteer

가속도 & 속도

Sparse encoder