i have following code : import pandas as pd import numpy as np import pandas as pd def…
- User
i have following code : import pandas as pd import numpy as np import pandas as pd
def fill_missing_hours_optimized(csv_file, output_file):
# Read CSV with appropriate date parsing (assuming 'Date' and 'Hour' columns) df = pd.read_csv(csv_file, parse_dates=['Date']) # Assuming 'Hour' column exists and needs combining with 'Date' for complete datetime index if 'Hour' in df.columns: df['Date'] = pd.to_datetime(df['Date']) + pd.to_timedelta(df.pop('Hour'), unit='h') # Set 'Date' as index for efficient resampling and manipulation df.set_index('Date', inplace=True) # Resample to hourly frequency, using ffill for existing non-null data df = df.resample('H').first().interpolate(method='time') # 'ffill' replaced with 'time'-based interpolation # For numeric columns, fill missing values with the mean of their day numeric_cols = df.select_dtypes(include=[np.number]).columns df[numeric_cols] = df[numeric_cols].transform(lambda x: x.fillna(x.mean())) # Interestingly, if there exist non-numeric columns that need special handling, # specific strategies need to be defined as .fillna() or similar based on context. # Drop unwanted columns with a single line thanks to list comprehension columns_to_remove = [col for col in df.columns if "Unix" in col] df.drop(columns=columns_to_remove, inplace=True) # Save the optimized and filled data to output CSV df.to_csv(output_file, index=False)Example usage
csv_file = r'E:\01_calculate_talib\New folder\Binance_1INCHBUSD_1h.csv' output_file = r'E:\01_calculate_talib\New folder\filled_data_3.csv' fill_missing_hours_optimized(csv_file, output_file)
print(f"Missing hours filled and saved to: {output_file}")
after doing operation my Date column is missing in output file fix it
- Assistant
The issue with the Date column being missing in the output file is because of the line
df.to_csv(output_file, index=False). The Date column has been set as the index and by specifyingindex=Falsewhen callingto_csv, you're telling pandas not to include the index (in this case, the Date column) in the output file. - User
and also i have a Symbol Columns which its value is string but not calculated for new added rows fix that problem too
- Assistant
- User
not calculating missing datas
- Assistant