Adding New Time Column to DataFrame
In order to plot your data, you need to transform the index column, 'YYYY-MO-DD HH-MI-SS_SSS', into a regular column. To achieve this, you can utilize the 'reset_index' function to convert the index to a new column.
df3 = df3.reset_index()
This will create a new column named 'index' in your DataFrame df3.
Alternatively, you can use the 'copy and assignment' method to create a new column based on the existing index:
df3['Time'] = df3.index
This will add a new column named 'Time' that contains the values from the index.
Optimized Code
Here's an optimized version of your code that addresses the issue:
# Import CSV file df = pd.read_csv('university2.csv', sep=";", skiprows=1, index_col='YYYY-MO-DD HH-MI-SS_SSS', parse_dates='YYYY-MO-DD HH-MI-SS_SSS') # Extract interesting columns df2 = df[[ 'ATMOSPHERIC PRESSURE (hPa)', 'TEMPERATURE (C)', 'magnetic_mag']].copy() # Resample and aggregate interesting columns df3 = df2.resample('H').agg(['mean','std']) df3.columns = [' '.join(col) for col in df3.columns] # Reset index to create Time column df3.reset_index(inplace=True) # Plot the data plt.plot(df3['magnetic_mag mean'], df3['Time'], label='FDI')
This optimized code uses 'read_csv' with proper options to set the index column and parse dates correctly. Additionally, it leverages 'inplace' functionality to avoid creating unnecessary copies of data.
The above is the detailed content of How to Convert a Datetime Index into a Regular Column in a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!