Home  >  Article  >  Backend Development  >  Empty pandas dataframe retaining data types

Empty pandas dataframe retaining data types

WBOY
WBOYforward
2024-02-22 13:10:19431browse

保留数据类型的空 pandas 数据框

Question content

I want to create an empty df as a template with reserved data types. code show as below:

import pandas as pd
import datetime
from dataclasses import dataclass

@dataclass
class openorder:
    symbol: str = "dummy"
    sectype: str = "stk"
    dt: datetime.datetime = datetime.datetime.now()
    price: float = 0.0
    status: str = none

    def empty(self):
        open_ord = self()
        empty_df = pd.dataframe([open_ord.__dict__])
        return empty_df.iloc[0:0]

Instantiation is valid, but clearing is invalid.

open_order = OpenOrder()
order_df = open_order.empty()

How can I do this?


Correct answer


You cannot call self() because self is a reference to an object, not to Class reference. Just use

def empty(self):
        empty_df = pd.DataFrame([self.__dict__])
        return empty_df.iloc[0:0]

The above is the detailed content of Empty pandas dataframe retaining data types. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete