You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Pandas中实现DataFrame行乘法运算(无需转数组)

Solution for Row-wise Product Calculation in Pandas (No Array Conversion)

Got it, let's tackle this without converting your DataFrame to arrays—Pandas has built-in functions that handle this cleanly, including skipping null values automatically.

Here's a step-by-step approach that keeps everything within Pandas:

1. Handle Decimal Separators (If Needed)

First, notice your sample data uses commas as decimal separators (like 0,03). Pandas expects dots for numeric values, so we'll convert those first if your actual data is stored as strings:

import pandas as pd

# Replace commas with dots and convert to float for all numeric columns
numeric_cols = df.select_dtypes(exclude=['object']).columns  # Or list your cols explicitly if needed
df[numeric_cols] = df[numeric_cols].replace(',', '.', regex=True).astype(float)

2. Calculate the Row-wise Product

We'll select all numeric columns, add 1 to each value, then compute the product across each row—with skipna=True to ignore null values:

# Select numeric columns (excludes the 'date' column automatically if it's a datetime/object type)
numeric_data = df.select_dtypes(include=['float64', 'int64'])

# Compute (1 + value) product per row, skipping nulls
row_product = (1 + numeric_data).prod(axis=1, skipna=True)

3. Build the New DataFrame

Finally, construct your desired output by combining the original date column with the calculated product values:

new_df = pd.DataFrame({
    'date': df['date'],
    'value': row_product
})

Why This Works

  • No array conversion required: All operations use Pandas' native DataFrame/Series methods, so you won't lose any data or metadata.
  • skipna=True (default for prod()) ensures any null cells in the numeric columns are skipped during the product calculation.
  • select_dtypes makes this flexible—if you add more numeric columns later (like F, G), the code will automatically include them without modification.

内容的提问来源于stack exchange,提问作者khouzam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:23:39