让我们采用一个简单的函数,它接受一个str并返回一个数据帧:
import pandas as pd
def csv_to_df(path):
return pd.read_csv(path, skiprows=1, sep='\t', comment='#')
Run Code Online (Sandbox Code Playgroud)
为此函数添加类型提示的推荐pythonic方法是什么?
如果我向python询问它返回的DataFrame的类型pandas.core.frame.DataFrame.以下内容不起作用,因为它会告诉我大熊猫没有定义.
def csv_to_df(path: str) -> pandas.core.frame.DataFrame:
return pd.read_csv(path, skiprows=1, sep='\t', comment='#')
Run Code Online (Sandbox Code Playgroud) My function returns a pandas series, where all elements have a specific type (say str). The following MWE should give an impression:
import pandas as pd
def f() -> pd.Series:
return pd.Series(['a', 'b'])
Run Code Online (Sandbox Code Playgroud)
Within the type hints I want to make clear, that f()[0] will always be of type str (compared for example to a function that would return pd.Series([0, 1])). My initial guess was to use def f() -> pd.Series[str]: what gives the TypeError: 'type' object is …
我正在编写一个返回 PandasDataFrame对象的函数。我希望有某种类型来暗示它DataFrame包含哪些列,而不仅仅是文档中的规范,因为我觉得这将使最终用户更容易读取数据。
在编辑 Python 文件和编辑 Jupyter Notebook 时,是否有办法输入DataFrameVisual Studio Code 和 PyCharm 等不同工具支持的提示内容?
一个示例函数:
def generate_data(bunch, of, inputs) -> pd.DataFrame:
"""Massages the input to a nice and easy DataFrame.
:return:
DataFrame with columns a(int), b(float), c(string), d(us dollars as float)
"""
Run Code Online (Sandbox Code Playgroud)