import pandas as pd from datetime import datetime, timedelta Load your CSV into a…
- User
import pandas as pd from datetime import datetime, timedelta
Load your CSV into a DataFrame
df = pd.read_csv(r"C:\Users\Fazel\Desktop\new data\extras\Defi_cap.csv", parse_dates=['Date'])
Ensure the Date column is datetime type (if not already)
df['Date'] = pd.to_datetime(df['Date'])
Create a complete date range from min to max
date_range = pd.date_range(start=df['Date'].min(), end=df['Date'].max())
Reindex the DataFrame using the complete date range, filling missing values with NaN
df_full = df.set_index('Date').reindex(date_range).reset_index().rename(columns={'index': 'Date'})
Function to fill missing values by averaging the previous and next rows
def fill_missing_with_mean(row, next_row, prev_row): return (next_row + prev_row) / 2
Iterate through the DataFrame and calculate mean for missing rows
for index, row in df_full.iterrows():
code# Skip if the row is not missing (not NaN) if not pd.isnull(row).any(): continue next_row = df_full.iloc[index + 1] # row after the missing row prev_row = df_full.iloc[index - 1] # row before the missing row # Calculate mean for all columns except Date for col in df_full.columns[1:]: df_full.at[index, col] = fill_missing_with_mean(row, next_row[col], prev_row[col])Output the updated DataFrame to a new CSV
df_full.to_csv(r"C:\Users\Fazel\Desktop\new data\extras\Defi_cap.csv", index=False)
cannot reindex on an axis with duplicate labels
- Assistant