Empty pandas dataframe retaining data types

WBOY
Release: 2024-02-22 13:10:19
forward
383 people have browsed it

保留数据类型的空 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]
Copy after login

Instantiation is valid, but clearing is invalid.

open_order = OpenOrder()
order_df = open_order.empty()
Copy after login

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]
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!