Notification texts go here Contact Us Buy Now!

Wrong datatime index in Pandas DataFrame with class

The provided code seems to display incorrectly because the 'moment' column in the DataFrame is not set as the index. The 'moment' column needs to be correctly set as the index for it to work as expected.

Fix:

class Records:
    def __init__(self):
        # Create an empty DataFrame with columns
        self.dfv = pd.DataFrame(columns=['moment', 'val'])

    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)

        # Set 'moment' as the index
        self.dfv.set_index('moment', inplace=True)

        return self.dfv

if __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

    dfv = pd.DataFrame(columns=['moment', 'val'])
    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)

In this corrected code, we create a DataFrame with columns 'moment' and 'val', append records to the DataFrame, and correctly set 'moment' as the index using set_index().

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.