【问题标题】:Convert string column to integer将字符串列转换为整数
【发布时间】:2017-02-03 06:53:07
【问题描述】:

我有一个如下所示的数据框

    a   b
0   1   26190
1   5   python
2   5   580

我想让列b 只承载整数,但正如您所见,python 不可转换,所以我想删除索引1 处的行。我的预期输出必须像

    a   b
0   1   26190
1   5   580

如何在python中使用pandas进行过滤和删除?

【问题讨论】:

标签: python string pandas numpy int


【解决方案1】:

您可以将to_numericnotnull 一起使用并按boolean indexing 过滤:

print (pd.to_numeric(df.b, errors='coerce'))
0    26190.0
1        NaN
2      580.0
Name: b, dtype: float64

print (pd.to_numeric(df.b, errors='coerce').notnull())
0     True
1    False
2     True
Name: b, dtype: bool

df = df[pd.to_numeric(df.b, errors='coerce').notnull()]
print (df)

   a      b
0  1  26190
2  5    580

Boud 评论的另一个解决方案 - 将 to_numericdropna 一起使用,最后由 astype 转换为 int

df.b = pd.to_numeric(df.b, errors='coerce')
df = df.dropna(subset=['b'])
df.b = df.b.astype(int)
print (df)
   a      b
0  1  26190
2  5    580

如果需要检查所有包含错误数据的行,请使用isnull - 在应用函数to_numeric 获取NaN 后过滤所有数据:

print (pd.to_numeric(df.b, errors='coerce').isnull())
0    False
1     True
2    False
Name: b, dtype: bool

print (df[pd.to_numeric(df.b, errors='coerce').isnull()])
   a       b
1  5  python

【讨论】:

    【解决方案2】:

    这应该可以工作

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'a' : [1, 5, 5],
                       'b' : [26190, 'python', 580]})
    df
       a       b
    0  1   26190
    1  5  python
    2  5     580
    
    df['b'] = np.where(df.b.str.contains('[a-z]') == True, np.NaN, df.b)
    df
       a      b
    0  1  26190
    1  5    NaN
    2  5    580
    
    df = df.dropna()
    df
       a      b
    0  1  26190
    2  5    580
    

    您使用正则表达式来识别字符串,然后使用np.where 将它们转换为np.NaN,然后使用df.dropna() 将它们从df 中删除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-15
      • 2015-01-14
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多