How to prevent Panda's itertuple method from adding extra decimals to records from a csv file? -Python
Question: I have a Python function that reads through a csv file and returns each row in
the csv in a tuple.

I'm using Python's Pandas library to achieve this.

The problem is after Pandas returns the tuple, it appends an extra decimal
point to records that looks like an integer. e.g `1001 becomes 1001.0`

Sample csv file:

    
    
    key1, key2
    a, '1001'
    b, '2002'
    

The code is something like this:

    
    
    import pandas as pd
    
    file_content_df = pd.read_csv(path_to_csv_file)
    
    for each_row in file_content_df.itertuples():
        row_item1, row_item2 = each_row
        print row_item1  # Prints 'a'
        print row_item2  # Prints 1001.0 (Desired result is 1001)
    

Is there a way to control this behavior pls ?!


Answer: First you can check [`dtypes`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.dtypes.html) if column `key2` is `int`
or `float` or `object` and then you can use second item by `each_row[1]` and
third item by `each_row[2]`:

    
    
    print df
      key1  key2
    0    a  1001
    1    b  2002
    
    print df.dtypes
    key1    object
    key2     int64
    dtype: object
    
    for each_row in df.itertuples():
        print each_row
        print each_row[1]
        print each_row[2]
        print '******'
    
    Pandas(Index=0, key1='a', key2=1001)
    a
    1001
    ******
    Pandas(Index=1, key1='b', key2=2002)
    b
    2002
    ******
    

If `dtypes` of column `key2` is `object` and `df` is like:

    
    
    print df
      key1    key2
    0    a  '1001'
    1    b  '2002'
    
    print df.dtypes
    key1    object
    key2    object
    dtype: object
    
    #remove ' and cast to integer
    df['key2'] = df['key2'].str.strip("'").astype(int)
    
    print df.dtypes
    key1    object
    key2     int32
    dtype: object
    
    for each_row in df.itertuples():
        print each_row
        print each_row[1]
        print each_row[2]
        print '******'
    
    Pandas(Index=0, key1='a', key2=1001)
    a
    1001
    ******
    Pandas(Index=1, key1='b', key2=2002)
    b
    2002
    ******
    

