在Pandas中实现DataFrame行乘法运算(无需转数组)
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 forprod()) ensures any null cells in the numeric columns are skipped during the product calculation.select_dtypesmakes this flexible—if you add more numeric columns later (like F, G), the code will automatically include them without modification.
内容的提问来源于stack exchange,提问作者khouzam

