如果数值数据类型列 pandas 数据框中的值为 str,则打印索引和值

print index and value if value is str in a numeric data type column pandas dataframe

我是数据科学的新手,目前我正在进一步探索。我有超过 600,000 列的数据集,我目前正在清理并检查它是否存在不一致或异常值。我遇到了一个我不确定如何解决的问题。我有一些解决方案,但我不确定如何使用 pandas.

我已经将某些列的数据类型从object 转换为int。我没有收到任何错误,并检查了它是否在 int 中。我检查了一列的值以检查事实数据。这涉及年龄,我收到一条错误消息,说我的专栏有一个字符串。所以我用这个方法检查了它:

print('if there is string in numeric column',np.any([isinstance(val, str) for val in homicide_df['Perpetrator Age']])

现在,我想打印所有索引及其值,并仅在具有字符串数据类型的这一列上键入。

目前我想出了这个工作正常的解决方案:

def check_type(homicide_df):
    for age in homicide_df['Perpetrator Age']:
        if type(age) is str:
            print(age, type(age))
check_type(homicide_df)

以下是我的一些问题:

  1. 是否有 pandas 方法来做同样的事情?
  2. 我应该如何将这些元素转换为 int?
  3. 为什么列中的某些元素没有转换为 int?

如有任何帮助,我将不胜感激。非常感谢

您可以使用 iteritems:

def check_type(homicide_df):
    for i, age in homicide_df['Perpetrator Age'].iteritems():
        if type(age) is str:
            print(i, age, type(age))

homicide_df = pd.DataFrame({'Perpetrator Age':[10, '15', 'aa']})
print (homicide_df)
  Perpetrator Age
0              10
1              15
2              aa


def check_type(homicide_df):
    for i, age in homicide_df['Perpetrator Age'].iteritems():
        if type(age) is str:
            print(i, age, type(age))

check_type(homicide_df)
1 15 <class 'str'>
2 aa <class 'str'>

如果值混合 - 数字与非数字,最好检查:

def check_type(homicide_df):
    return homicide_df.loc[homicide_df['Perpetrator Age'].apply(type)==str,'Perpetrator Age']

print  (check_type(homicide_df))
1    15
2    aa
Name: Perpetrator Age, dtype: object

如果所有值都是数字,但所有 type 都是 str:

print ((homicide_df['Perpetrator Age'].apply(type)==str).all())
True

homicide_df = pd.DataFrame({'Perpetrator Age':['10', '15']})

homicide_df['Perpetrator Age'] = homicide_df['Perpetrator Age'].astype(int)
print (homicide_df)

   Perpetrator Age
0               10
1               15

print (homicide_df['Perpetrator Age'].dtypes)
int32

但是如果一些带有字符串的数字:

使用 to_numeric 转换为 int 的解决方案,将非数值替换为 NaN。然后有必要将 NaN 替换为 0 之类的数字,最后转换为 int:

homicide_df = pd.DataFrame({'Perpetrator Age':[10, '15', 'aa']})

homicide_df['Perpetrator Age']=pd.to_numeric(homicide_df['Perpetrator Age'], errors='coerce')
print (homicide_df)
   Perpetrator Age
0             10.0
1             15.0
2              NaN

homicide_df['Perpetrator Age'] = homicide_df['Perpetrator Age'].fillna(0).astype(int)
print (homicide_df)
   Perpetrator Age
0               10
1               15
2                0