A tool to convert DataFrame to a list of objects of some class or vice versa
Project description
A tool to convert DataFrame to a list of objects of some class or vice versa
- Signatures
def df2obs(df: pd.DataFrame, clazz: Any) -> List[Any]
or
def obs2df(obs: List[Any]) -> pd.DataFrame
How to use
- Define class attribute : pandas DataFrame column mapping in your class directly
- Inherit your class from df2obs.base.Base, and make df2obs.base.BaseType as its metaclass
- You are ready to go using df2obs() and/or obs2df()
Example
import pandas as pd
from df2obs.base import Base, BaseType
movie_df = pd.DataFrame({
'title1': ['The American President', "Queen's Gambit", 'Wall Street'],
'year1': [1995, 2020, 1987],
'director2': ['Rob Reiner', 'Scott Frank', 'Oliver Stone']
})
class Movie(Base, metaclass=BaseType):
# class attribute = pandas DataFrame column name
title = 'title1'
year = 'year1'
director = 'director2'
if __name__ == "__main__":
m = Movie()
packed_obs = list(m.df2obs(movie_df))
print(packed_obs)
print('='*100)
print(m.obs2df(packed_obs))
Result:
[{'title': 'The American President', 'year': 1995, 'director': 'Rob Reiner'}, {'title': "Queen's Gambit", 'year': 2020, 'director': 'Scott Frank'}, {'title': 'Wall Street', 'year': 1987, 'director': 'Oliver Stone'}]
====================================================================================================
title year director
0 The American President 1995 Rob Reiner
1 Queen's Gambit 2020 Scott Frank
2 Wall Street 1987 Oliver Stone
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
df2obs-0.1.0.tar.gz
(2.6 kB
view details)
Built Distribution
File details
Details for the file df2obs-0.1.0.tar.gz
.
File metadata
- Download URL: df2obs-0.1.0.tar.gz
- Upload date:
- Size: 2.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.25.0 setuptools/41.4.0 requests-toolbelt/0.9.1 tqdm/4.54.1 CPython/3.7.3
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 268d09894e884270c3fcc39dbd74d9274384205a9cacf1e7c174cd05a1c85b85 |
|
MD5 | a73a1fe191a5637fc44c294dd1ebc7e8 |
|
BLAKE2b-256 | d3051b29477cbc2fcb3cbd5c49a16bab189f90f999d7b2c76ded758925c1493f |
Provenance
File details
Details for the file df2obs-0.1.0-py3-none-any.whl
.
File metadata
- Download URL: df2obs-0.1.0-py3-none-any.whl
- Upload date:
- Size: 2.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.25.0 setuptools/41.4.0 requests-toolbelt/0.9.1 tqdm/4.54.1 CPython/3.7.3
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | d74dd4d4b4114f899fa04f491ee29f1c16244ef563a5ff0acee7f5a8ffacf237 |
|
MD5 | 0c3ece7cbb0036c5c6b462196ac37386 |
|
BLAKE2b-256 | 8cc52e5d8652d1c90f4cd0d5261ac46244982a26a611ed9e63dacb884495a4a1 |