【问题标题】:Deleting all array values that are non-numeric删除所有非数字的数组值
【发布时间】:2019-08-21 23:21:30
【问题描述】:

我有一个要清理的数组,其中包含以下条目:

arr = (['1140.0', '-600.0', '-700.6', '5700.45', '(~par)', '(-6.0', '690.6', ....., 
'-----', '5750.65', '#', '-850.0'])

我想清理这个包含所有 non-numeric 值的数组,并在数组中保持顺序以获得如下输出:

arr_clean = (['1140.0', '-600.0', '-700.6', '5700.45', '690.6', '5750.65', '-850.0'])

有些值是负数,所以我不能简单地查看元素的第一个字符是否是非数字的,有些值中有数字但也需要取出 - 比如值(-6.0

我首先转换为数据框,看看是否可以更改 pd.to_numeric(df[col]) 并以这种方式清理它,但从数组到 df 再切换回来感觉效率不高(数组的大小为~800,000,我希望我的最终输出是一个数组)。

有没有简单的方法可以做到这一点?

【问题讨论】:

  • array 是指 Python 列表吗?如果是这样,为什么是()?或者这是一个 numpy ndarray?如果是这样,形状和dtype是什么?

标签: python arrays python-3.x string pandas


【解决方案1】:

如果我可以假设您的 array 在数据框中,您可以使用 pd.to_numericerrors=coerce,然后使用 Dataframe.dropna

# Example dataframe which was provided
data = {'Array':['1140.0', '-600.0', '-700.6', '5700.45', '(~par)', '(-6.0', '690.6', '.....', '-----', '5750.65', '#', '-850.0']}

df = pd.DataFrame(data)
print(df)
      Array
0    1140.0
1    -600.0
2    -700.6
3   5700.45
4    (~par)
5     (-6.0
6     690.6
7     .....
8     -----
9   5750.65
10        #
11   -850.0

申请pd.to_numeric

pd.to_numeric(df.Array, errors='coerce').dropna()

0     1140.00
1     -600.00
2     -700.60
3     5700.45
6      690.60
9     5750.65
11    -850.00
Name: Array, dtype: float64

【讨论】:

  • 我只是针对我的解决方案进行了基准测试,它需要 445 毫秒,比我的 670 毫秒快 33%(但设置时间更长)。
【解决方案2】:

float('(-6.0') 不是数字时会抛出异常。使用此功能非常符合 Pythonic (duck typing):

arr = (['1140.0', '-600.0', '-700.6', '5700.45', '(~par)', '(-6.0', '690.6', '...',
'-----', '5750.65', '#', '-850.0'])

arr_clean = list()

for elm in arr:
    try:
        float(elm)
        print("could     convert string to float:", elm)
        arr_clean.append(elm)
    except ValueError as e:
        print(e)

print(arr_clean)

这个输出:

could     convert string to float: 1140.0
could     convert string to float: -600.0
could     convert string to float: -700.6
could     convert string to float: 5700.45
could not convert string to float: '(~par)'
could not convert string to float: '(-6.0'
could     convert string to float: 690.6
could not convert string to float: '...'
could not convert string to float: '-----'
could     convert string to float: 5750.65
could not convert string to float: '#'
could     convert string to float: -850.0
['1140.0', '-600.0', '-700.6', '5700.45', '690.6', '5750.65', '-850.0']

【讨论】:

  • 有没有比遍历所有元素更有效的方法?仅根据我的实际数组的大小(大约 800,000 个元素),它可能需要太多的计算能力。
  • 任何过滤都至少需要O(n),除非您将任务并行化,或者将其下推到较低级别的代码。老实说,我希望设置并行化需要更长的时间然后只是这样做......另外,我刚刚在 800 000 上测试了 50/50 字符串与数字,运行时间为 670 毫秒。这对您的用例来说太慢了吗?嗯,当你运行它时,你是否保留了打印语句?确保删除它们,否则将花费更长的时间。在最后一行使用关键字pass 而不是print(e),然后删除另一个。
猜你喜欢
  • 2012-06-18
  • 1970-01-01
  • 2018-01-31
  • 1970-01-01
  • 2012-06-24
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 2012-07-12
相关资源
最近更新 更多