杰瑞科技汇

Python单元格值如何高效读取与修改?

Of course! The term "Python cell value" most commonly refers to getting or setting the value of a cell within a Jupyter Notebook. However, it can also refer to values in a pandas DataFrame or an Excel sheet accessed via Python.

Python单元格值如何高效读取与修改?-图1
(图片来源网络,侵删)

Let's break down the most common scenarios.


In a Jupyter Notebook (IPython)

This is the most direct interpretation. A "cell" is a block of code or text in a Jupyter Notebook. The "value" of a cell is the result of executing its code.

Getting the Value (Output) of a Cell

When you run a code cell, its output is displayed directly below it. This output is the cell's "value".

# This is a code cell.
# Its "value" is the output it produces when run.
print("Hello from Cell 1!")
x = 10 * 5
print(f"The result is: {x}")

When you run this cell, you see the output:

Python单元格值如何高效读取与修改?-图2
(图片来源网络,侵删)
Hello from Cell 1!
The result is: 50

This printed text is the cell's value.

Storing a Cell's Value for Use in Another Cell

You can't directly "get" the value of a previous cell as an object, but you can store its result in a variable and use that variable in subsequent cells. This is the standard workflow.

Cell 1:

# Perform a calculation and store the result in a variable.
# This is often called a "code cell that produces output".
my_calculation = 25 ** 2 
print(f"Calculation complete. Result is: {my_calculation}")

Output:

Calculation complete. Result is: 625

Cell 2:

# Now, you can use the variable from the previous cell.
# The variable 'my_calculation' is in memory.
print(f"Using the value from the other cell: {my_calculation}")
print(f"Let's do something else with it: {my_calculation / 10}")

Output:

Using the value from the other cell: 625
Let's do something else with it: 62.5

Getting the Source Code of a Cell

If you want to programmatically get the code inside a cell (not its output), you can use the IPython API. This is an advanced technique.

# This code will only work in a Jupyter Notebook or IPython environment.
from IPython import get_ipython
# Get the handle for the current IPython instance
ipython = get_ipython()
# Get the source code of the previous cell (index -1)
# Note: This can be unreliable and is not standard practice for most users.
previous_cell_source = ipython.history_manager.get_tail(1)[0][2]
print("The source code of the previous cell was:")
print(previous_cell_source)

In a Pandas DataFrame

This is a very common task in data analysis. A DataFrame is like a spreadsheet, and a "cell" is an intersection of a row and a column.

Getting a Cell Value

You can get a cell's value using .at[] (for fast label-based access) or .iat[] (for fast integer-position-based access). .loc[] and .iloc[] are more general and also work.

import pandas as pd
# Create a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35],
        'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
print("-" * 20)
# --- Get a cell value ---
# Method 1: .at[] (Recommended for single value, label-based)
# Get the age of 'Bob'
age_of_bob = df.at[1, 'Age']
print(f"Bob's age (using .at[]): {age_of_bob}")
# Method 2: .loc[] (Label-based, more flexible)
# Get the city of the person at index 2
city_of_charlie = df.loc[2, 'City']
print(f"Charlie's city (using .loc[]): {city_of_charlie}")
# Method 3: .iat[] (Integer-position-based, very fast)
# Get the value in row 0, column 1
name_of_alice = df.iat[0, 1]
print(f"Alice's name (using .iat[]): {name_of_alice}")

Setting a Cell Value

Setting a value is just as easy.

import pandas as pd
# Using the same DataFrame from above
print("Original DataFrame:")
print(df)
print("-" * 20)
# --- Set a cell value ---
# Method 1: .at[]
df.at[1, 'Age'] = 31 # Update Bob's age
print("DataFrame after updating Bob's age:")
print(df)
print("-" * 20)
# Method 2: .loc[]
df.loc[2, 'City'] = 'Houston' # Update Charlie's city
print("DataFrame after updating Charlie's city:")
print(df)

In an Excel File (using openpyxl or pandas)

If you mean a cell in an Excel file that Python is reading from or writing to, you would use a library like openpyxl.

Getting a Cell Value

from openpyxl import load_workbook
# Load an existing Excel file
# Make sure 'my_data.xlsx' exists in the same folder
try:
    wb = load_workbook(filename='my_data.xlsx')
    sheet = wb.active
    # Get the value from cell A1
    value_a1 = sheet['A1'].value
    print(f"Value in cell A1: {value_a1}")
    # Get the value from cell B2 using row/column notation
    value_b2 = sheet.cell(row=2, column=2).value
    print(f"Value in cell B2: {value_b2}")
except FileNotFoundError:
    print("Error: 'my_data.xlsx' not found. Please create this file first.")

Setting a Cell Value

from openpyxl import Workbook
# Create a new workbook and select the active sheet
wb = Workbook()
ws = wb.active= "Data"
# Set values in specific cells
ws['A1'] = "Product"
ws['B1'] = "Price"
ws['A2'] = "Apple"
ws['B2'] = 1.99
ws['A3'] = "Banana"
ws['B3'] = 0.79
# Save the workbook
wb.save("products.xlsx")
print("Excel file 'products.xlsx' created successfully.")

Summary

Context What is a "Cell"? How to Get the Value How to Set the Value
Jupyter Notebook A block of code or text. The output is displayed below. Store results in variables to use them in other cells. N/A (You edit the code directly).
Pandas DataFrame A row/column intersection. df.at[row_label, col_label]
df.loc[row_label, col_label]
df.iat[row_int, col_int]
df.at[row, col] = new_value
df.loc[row, col] = new_value
Excel File A spreadsheet intersection (e.g., A1). sheet['A1'].value
sheet.cell(row=1, column=1).value
sheet['A1'] = new_value
sheet.cell(row=1, column=1).value = new_value
分享:
扫描分享到社交APP
上一篇
下一篇