【问题标题】:python check if dataframe column contains string with specific lengthpython检查数据框列是否包含具有特定长度的字符串
【发布时间】:2021-07-29 09:26:46
【问题描述】:

我需要创建一个函数来检查数据框列中字符串的长度。

我有这个代码

df['XXX'] = df['XXX'].map(lambda x: x if isinstance(x, (datetime)) else None)
df_col_len = int(df['XXX']].str.encode(encoding='utf-8').str.len().max())
if df_col_len > 4:
  print("In this step it will send a email")

问题是我有大约 20 列,每列应该有不同的长度。

我需要检查第 1 列是否最大长度

您知道如何一次检查必要的列吗?

谢谢

【问题讨论】:

  • 上传你的源 csv 样本(作为文件或文本)......并告诉你的确切要求(没有像“等”这样的模棱两可的词)

标签: python string dataframe lambda


【解决方案1】:

您可以在数据帧上使用.lt(低于):

样本数据:

import pandas as pd
import numpy as np

d1 = {'A': {0: 'a', 1: 'ab', 2: 'abc'}, 'B': {0: 'abcd', 1: 'abcde', 2: 'abcdef'}, 'C': {0: 'abcdefg', 1: 'abcdefge', 2: 'abcdefgeh'}}
df = pd.DataFrame(d1)

代码:

max_len = {'A': 2, 'B': 5, 'C': 10}

# return length of element in your dataframe
df_check = df.applymap(len)
# create a new auxiallry dataframe with the values you want as a maximum
df_max = pd.DataFrame(np.repeat(pd.DataFrame(max_len, index=[1]).values, len(df), axis=0), columns=df.columns)

# check if the length of the actual value are *lower than* their max
df_check.lt(df_max)

输出:

Input, looks like:

     A       B          C
0    a    abcd    abcdefg
1   ab   abcde   abcdefge
2  abc  abcdef  abcdefgeh


Output, looks like:

       A      B     C
0   True   True  True
1  False  False  True
2  False  False  True

补充说明:

要找到列名,您可以查看此question

【讨论】:

    猜你喜欢
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多