pandas read_csv 跳过行不工作

2024-10-03 04:38:47 发布

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

我试图跳过一些包含错误值的行。在

这是我不使用skiprows参数从文件中读入的数据。在

>> df    
         MstrRecNbrTxt  UnitIDNmb  PersonIDNmb  PersonTypeCde
2194593              P        NaN          NaN            NaN
2194594      300146901        1.0          1.0            1.0
4100689            DAT        NaN          NaN            NaN
4100690      300170330        1.0          1.0            1.0
5732515             DA        NaN          NaN            NaN
5732516      300174170        2.0          1.0            1.0

我想跳过2194593、4100689和5732515行。我希望在表中看不到我读入的那些行。在

^{pr2}$

但当我再次打印时,这些行仍然存在。在

>> df
        MstrRecNbrTxt  UnitIDNmb  PersonIDNmb  PersonTypeCde
2194593              P        NaN          NaN            NaN
2194594      300146901        1.0          1.0            1.0
4100689            DAT        NaN          NaN            NaN
4100690      300170330        1.0          1.0            1.0
5732515             DA        NaN          NaN            NaN
5732516      300174170        2.0          1.0            1.0

数据如下:

{'PersonIDNmb': {2194593: nan,
          2194594: 1.0,
          4100689: nan,
          4100690: 1.0,
          5732515: nan,
          5732516: 1.0},
         'PersonTypeCde': {2194593: nan,
          2194594: 1.0,
          4100689: nan,
          4100690: 1.0,
          5732515: nan,
          5732516: 1.0},
         'UnitIDNmb': {2194593: nan,
          2194594: 1.0,
          4100689: nan,
          4100690: 1.0,
          5732515: nan,
          5732516: 2.0},
         '\ufeffMstrRecNbrTxt': {2194593: 'P',
          2194594: '300146901',
          4100689: 'DAT',
          4100690: '300170330',
          5732515: 'DA',
          5732516: '300174170'}}

我做错什么了?在

我的最终目标是去掉dataframe中的NaN值,这样数据就可以作为整数而不是浮点形式读入(因为很难将这个表连接到其他非浮点表)。在


Tags: 数据df参数错误nandadat浮点
1条回答
网友
1楼 · 发布于 2024-10-03 04:38:47

工作示例。。。希望这有帮助!在

from io import StringIO
import pandas as pd
import numpy as np

txt = """index,col1,col2
0,a,b
1,c,d
2,e,f
3,g,h
4,i,j
5,k,l
6,m,n
7,o,p
8,q,r
9,s,t
10,u,v
11,w,x
12,y,z"""

indices_to_skip = np.array([2, 6, 11])
# I offset `indices_to_skip` by one in order to account for header
df = pd.read_csv(StringIO(txt), index_col=0, skiprows=indices_to_skip + 1)
print(df)

      col1 col2
index          
0        a    b
1        c    d
3        g    h
4        i    j
5        k    l
7        o    p
8        q    r
9        s    t
10       u    v
12       y    z

相关问题 更多 >