0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pandasのSeriesの要素の中で最大の桁数・文字数を取得する

Last updated at Posted at 2023-10-29

関数

import pandas as pd

def max_digits(series):
    """
    pandasのSeriesが与えられたとき、Seriesが数値型の場合は数値の最大桁数を返し、文字列型の場合は最大文字数を返す。

    引数:
        series (pd.Series): pandasのSeries

    戻り値:
        int: Seriesの要素の中の最大の桁数もしくは文字数
    """
    # seriesが空の場合は0を返す
    if len(series) == 0:
        return 0

    # seriesの型に応じて処理を分ける
    # seriesが数値型の場合は数値の桁数を返す
    if series.dtype == 'int64':
        return int(series.abs().apply("log10").max()) + 1
    # seriesが浮動小数点型の場合は小数点以下の桁数を返す
    elif series.dtype == 'float64':
        return series.abs().astype(str).str.len().max()-1
    # seriesが文字列型の場合は文字数を返す
    elif series.dtype == 'object':
       return series.str.len().max()

使用例

# 整数(正の値): 最大桁数を返します
print(max_digits(pd.Series([123, 45678, 9, 123456789])))  # 9

# 整数(負の値): 絶対値の最大桁数を返します
print(max_digits(pd.Series([123, 45678, 9, -123456789])))  # 9

# 小数: 整数部分と小数部分の桁数を足した最大桁数を返します
print(max_digits(pd.Series([123, 45678, 9, 123456, -1.23456789]))) # 9

# 文字列: 文字数を返します
print(max_digits(pd.Series(['A', 'BB', 'CCC', 'DDDD'])))  # 4

# 空のSeries: 0を返します
print(max_digits(pd.Series([], dtype=float)))  # 0
0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?