【问题标题】:Checking the type for multi and single dimensional arrays Pandas Python检查多维和单维数组的类型 Pandas Python
【发布时间】:2021-05-19 00:24:22
【问题描述】:

我想检查MultiSingle 是浮点型还是字符串型。我如何能够检查multi dimensional 数组和single dimensional 数组的类型。

csv 文件:

Multi,Single    
[[20]|[yes]],[35|50]

代码:

import pandas pd

check = pd.read_csv("file.csv")
if (not isinstance(check["Multi"], (float, int))):
    print(f'Invalid value: {check["Multi"]} must be int or float')

if (not isinstance(check["Single"], (float, int))):
    print(f'Invalid value: {check["Single"]} must be int or float')

错误:

Invalid value: [[20]|[yes]] must be int or float

【问题讨论】:

  • 正在尝试分别查看 20 和是吗? [[20]|[yes]] 作为字符串读入,这就是正在测试的内容。 [35|50] 也一样,这是一个字符串。

标签: arrays python-3.x pandas if-statement multidimensional-array


【解决方案1】:

输入数据:

df = pd.read_csv(io.StringIO("""Multi,Single
[[20]|[yes]],[35|50]
[[20.5]|[-30.8]],[35.5|True]"""))
>>> df
              Multi       Single
0      [[20]|[yes]]      [35|50]  # Expect: Multi->False, Single->True
1  [[20.5]|[-30.8]]  [35.5|True]  # Expect: Multi->True, Single->False

首先,我们保留所有不是[|] 的字符,并尝试将它们转换为float

out = df.apply(lambda sr: sr.str.findall(r'([^\[\|\]]+)')
                                .apply(lambda l: pd.Series(l)
                                                   .astype(float, errors="ignore")
                                                   .dtype == float))
>>> out
   Multi  Single
0  False    True
1   True   False

【讨论】:

    猜你喜欢
    • 2018-06-01
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    相关资源
    最近更新 更多