代码之家  ›  专栏  ›  技术社区  ›  eega

熊猫数列小数点后最大位数的求法

  •  0
  • eega  · 技术社区  · 7 年前

    我设法得到随机生成的数字的位数,如下所示:

    df = pd.Series(np.random.rand(100)*1000) precision_digits = (df - df.astype(int)).astype(str).str.split(".", expand=True)[1].str.len().max()

    但是,如果我使用pd.read_csv从磁盘读取数据,其中一些行是空的(因此填充了nan),则会出现以下错误: Traceback (most recent call last): File "<input>", line 1, in <module> File "/home/tgamauf/workspace/mostly-sydan/venv/lib/python3.6/site-packages/pandas/core/generic.py", line 4376, in __getattr__ return object.__getattribute__(self, name) AttributeError: 'DataFrame' object has no attribute 'str'

    这里出什么事了? 有没有更好的方法做我需要的?

    2 回复  |  直到 7 年前
        1
  •  1
  •   jeschwar    7 年前

    pd.read_csv() 通常返回 DataFrame StringMethods 使用返回的对象 .str 仅为 Series 反对。尝试使用 pd.read_csv('your_data.csv' , squeeze=True) 系列 .str段

        2
  •  0
  •   BENY    7 年前

    NaN 在里面。

    df=pd.Series([1.111,2.2,3.33333,np.nan])
    

    idx=df.index# record the original index 
    df=df.dropna()# remove the NaN row 
    (df - df.astype(int)).astype(str).str.split(".", expand=True)[1].str.len().reindex(idx)
    
        3
  •  0
  •   Krzysztof Słowiński    6 年前

    版本 df - df.astype(int) str.split 没有它:

    def get_max_decimal_length(df):
        """Get the maximum length of the fractional part of the values or None if no values present."""
        values = df.dropna()
        return None if values.empty else values.astype(str).str.split(".", expand=True)[1].str.len().max()