打印索引和值,如果值是数字数据类型列pandas数据框中的字符串。

2024-04-25 22:59:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我是数据科学的新手,目前我正在进一步探索。我有超过600000列的数据集,我目前正在清理和检查不一致性或离群值。我遇到了一个我不知道如何解决的问题。我心里有一些解决办法,但我不知道怎么用熊猫。在

我已经把一些列的数据类型从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. 有没有熊猫做同样的事情的方法?在
  2. 如何将这些元素转换为int?在
  3. 为什么列上的一些元素没有转换成int?在

我会很感激你的帮助。非常感谢


Tags: 数据方法字符串indfageifis
1条回答
网友
1楼 · 发布于 2024-04-25 22:59:04

您可以使用^{}

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

^{pr2}$

如果值是混合的-数字和非数字,最好是检查:

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

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

^{}将非数值替换为NaNint的解决方案。然后有必要将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

相关问题 更多 >

    热门问题