Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic type hints with pandas?

Let's take a simple function that takes a str and returns a dataframe:

import pandas as pd def csv_to_df(path):     return pd.read_csv(path, skiprows=1, sep='\t', comment='#') 

What is the recommended pythonic way of adding type hints to this function?

If I ask python for the type of a DataFrame it returns pandas.core.frame.DataFrame. The following won't work though, as it'll tell me that pandas is not defined.

 def csv_to_df(path: str) -> pandas.core.frame.DataFrame:      return pd.read_csv(path, skiprows=1, sep='\t', comment='#') 
like image 807
dangom Avatar asked May 10 '17 11:05

dangom


People also ask

Does Python have type hints?

Python's type hints provide you with optional static typing to leverage the best of both static and dynamic typing. Besides the str type, you can use other built-in types such as int , float , bool , and bytes for type hintings. To check the syntax for type hints, you need to use a static type checker tool.

How do you type hint in Python?

Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.

How do I check pandas type?

To check the data type in pandas DataFrame we can use the “dtype” attribute. The attribute returns a series with the data type of each column. And the column names of the DataFrame are represented as the index of the resultant series object and the corresponding data types are returned as values of the series object.

Are type hints enforced in Python?

Python will always remain a dynamically typed language. However, PEP 484 introduced type hints, which make it possible to also do static type checking of Python code. Unlike how types work in most other statically typed languages, type hints by themselves don't cause Python to enforce types.


1 Answers

Why not just use pd.DataFrame?

import pandas as pd def csv_to_df(path: str) -> pd.DataFrame:     return pd.read_csv(path, skiprows=1, sep='\t', comment='#') 

Result is the same:

> help(csv_to_df) Help on function csv_to_df in module __main__: csv_to_df(path:str) -> pandas.core.frame.DataFrame 
like image 99
Georgy Avatar answered Sep 19 '22 14:09

Georgy