Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 16418

Wrong datatime index in Pandas DataFrame with class

$
0
0

I have a Pandas DataFrame with and without class. In case of class I have wrong datatime index but if no class it is ok. Please help.

from datetime import datetimeimport pandas as pdclass Records:    def __init__(self):        columns = ['moment', 'val']        # Create an empty DataFrame with columns        self.dfv = pd.DataFrame(columns=columns)    def add(self, moment, val):        # Record        rec = {'moment': moment, 'val': val}        # Convert 'moment' to datetime        rec['moment'] = pd.to_datetime(rec['moment'], format='%Y-%m-%d %H:%M:%S')        # Add the record to DataFrame        self.dfv = self.dfv.append(rec, ignore_index=True)        self.dfv['moment'] = pd.to_datetime(self.dfv['moment'])        self.dfv.set_index('moment', inplace=True)        return self.dfvif __name__ == '__main__':    print('=============================Class records===================')    r = Records()    df = r.add('2023-11-01 10:00:00', 100.0)    print(df)    df = r.add('2023-11-01 11:00:00', 120.0)    # Print the updated DataFrame    print(df)    df.info()    print('=============================Single records==================')    # Test first column datatime as an index    columns = ['moment', 'val']    dfv = pd.DataFrame(columns=columns)    dfv['moment'] = pd.to_datetime(dfv['moment'])    dfv.set_index('moment', inplace=True)    rec = {'moment': '2023-11-01 10:00:00', 'val': 100.0}    # Convert 'moment' to datetime    rec['moment'] = pd.to_datetime(rec['moment'], format='%Y-%m-%d %H:%M:%S')    # Add the record to DataFrame    dfv = dfv.append(rec, ignore_index=True)    # Set 'moment' as the index    rec2 = {'moment': '2023-11-01 11:00:00', 'val': 120.0}    dfv = dfv.append(rec2, ignore_index=True)    # Set 'moment' as the index    dfv.set_index('moment', inplace=True)    print(dfv)    dfv.info()    exit(0)

an output

=============================Class records===================                       valmoment                    2023-11-01 10:00:00  100.0                       valmoment                    NaT                  100.02023-11-01 11:00:00  120.0<class 'pandas.core.frame.DataFrame'>DatetimeIndex: 2 entries, NaT to 2023-11-01 11:00:00Data columns (total 1 columns): #   Column  Non-Null Count  Dtype  ---  ------  --------------  -----   0   val     2 non-null      float64dtypes: float64(1)memory usage: 32.0 bytes=============================Single records==================                       valmoment                    2023-11-01 10:00:00  100.02023-11-01 11:00:00  120.0<class 'pandas.core.frame.DataFrame'>Index: 2 entries, 2023-11-01 10:00:00 to 2023-11-01 11:00:00Data columns (total 1 columns): #   Column  Non-Null Count  Dtype  ---  ------  --------------  -----   0   val     2 non-null      float64dtypes: float64(1)memory usage: 32.0+ bytes

So with no class I have exactly what I want to get but if I use class (and I need to use class for my purposes) I have NaT as a first record index value . Please advise how to have a correct code with class. Thanks.


Viewing all articles
Browse latest Browse all 16418

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>