如何把一个列有对象d型浮在一个大熊猫据框?

0

的问题

我有一个数据框一列名为'高'我想转换值为浮动。 默认的单位是米,但它有一些价值在不正确的格式,或在英寸。 它看起来像

        height
0          16
1           7
2           7
3         6 m
4        2.40
5        5'8"
6          3m
7         6,9
8       9;6;3
9     Unknown
10       4.66
11 Bilinmiyor
12     11' 4"

dtype: object

基本上,我需要转换价值在英寸/ft计单元,把价值等 BilinmiyorUnknownNaN中,删除该单元规范喜欢 m m,替代逗号中的数字与 .,保持最大的数值 9;6;3. 最后dtypes应浮动或int。

我是新来的python所以我真的不知道如何使用先进技术为止。 我是在努力实现该任务使用

def to_num(a):
    try:
        return float(pd.to_numeric(a, errors = 'raise'))
    except ValueError:
        return a

df['height'] = to_num(df['height'])

但它没有工作。 我想知道我是否应该使用的迭代,但它似乎非常复杂的迭代过所有的细胞在此列,因为该数据集已经超过2亿行。

pandas python
2021-11-24 04:44:20
1

最好的答案

0

我觉得你的伙伴,我有同样的问题。 但值得庆幸的是这不是那么难

import pandas as pd

df = pd.DataFrame({'height': [16, 7, '6m', '2.4', '3,5', 'Asdf', '9;6;3']})
df['height'] = df['height'].astype(str)  # force type str
df['height'] = df['height'].str.replace('.', ',', regex=False)  # . -> ,
df['height'] = df['height'].str.replace('[A-Za-z]', '')  # remove all characters (regex)
df['height'] = df['height'].str.split(';').apply(max)  # pick largest value from 9;6;3
df['height'] = pd.to_numeric(df['height'], errors='coerce')  # force float

你会得到

height
0   16.0
1   7.0
2   6.0
3   2.4
4   3.5
5   NaN
6   9.0

现在,如果你想把你的脚米(我是默认的假设是米),则需要增加一个级别的肤色

import pandas as pd
import numpy as np
import re

def feet_to_m(s):
    if '\'' in s or "\"" in s:
        if '\'' in s:
            feet = float(s.split('\'')[0])
        else:
            feet = 0
        if '\"' in s:
            if '\'' in s:
                inch = float(s.split('\'')[1].split('\"')[0])
            else:
                inch = float(s.split('\"')[0])
        else:
            inch = 0
        return (feet*12 + inch) * 0.0254
    else:
        return s

df = pd.DataFrame({'height': [16, 7, '6m', '2.4', '3,5', 'Asdf', '9;6;3', "11' 4\"", "4'", "15\""]})
df['height'] = df['height'].astype(str)  # force type str
df['height'] = df['height'].str.replace(',', '.', regex=False)  # . -> ,
df['height'] = df['height'].str.replace('[A-Za-z]', '')  # remove all characters
df['height'] = df['height'].str.split(';').apply(max)  # pick largest value from 9;6;3
df['height'] = df['height'].apply(feet_to_m)
df['height'] = pd.to_numeric(df['height'], errors='coerce')  # force float

得到

height
0   16.0000
1   7.0000
2   6.0000
3   2.4000
4   3.5000
5   NaN
6   9.0000
7   3.4544
8   1.2192
9   0.3810

希望这可以帮助

2021-11-24 06:02:07

其他语言

此页面有其他语言版本

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................