DataFrame.apply converts integer data to float even in absence of mixed numerical types

I am using DataFrame.apply() to calculate a new “Metric” column by taking an existing integer categorical column and looking up the integer in a list, i.e., indexing into the list. It works fine when I use list comprehension, but when I use DataFrame.apply(), I get an error about the integer being used as an index is not an integer.

When I set the Spyder parameter to enter debug after an error, it places the program counter on the apply statement. I queried the intermediate results and confirmed that what should be an integer becomes a float.

Here is the test code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import numpy as np
import pandas as pd
import seaborn as sns # Generates 3-tuples in original application
nObservations = 4 # Number of rows
nIntCategory = 4 # Number of categories in the categorical integer column
dfObservations = pd.DataFrame()
# Categorical data column
dfObservations['IntCategory'] = np.random.randint(nIntCategory,size=nObservations)
# IntCategory
# 1
# 0
# 3
# 2
# Table to look up "Metric" value based on "IntCategory"
Cat2metric = np.random.random(nIntCategory)
# array([0.02190873, 0.9570024 , 0.34785749, 0.13852149])
# Create the "Metric" column via table lookup in Cat2metric
# Whether to use apply instead of list comprehension
ifUseApplyNotComprehension = True
if ifUseApplyNotComprehension: # Creates error in the comment below
dfObservations['Metric'] =
dfObservations.apply( lambda row: Cat2metric[ row.IntCategory ] , axis=1 )
# Index error [1]: list indices must be integers or slices,
# not numpy.float64
else: # No errors
dfObservations['Metric'] =
[ Cat2metric[i] for i in dfObservations.IntCategory ]
</code>
<code>import numpy as np import pandas as pd import seaborn as sns # Generates 3-tuples in original application nObservations = 4 # Number of rows nIntCategory = 4 # Number of categories in the categorical integer column dfObservations = pd.DataFrame() # Categorical data column dfObservations['IntCategory'] = np.random.randint(nIntCategory,size=nObservations) # IntCategory # 1 # 0 # 3 # 2 # Table to look up "Metric" value based on "IntCategory" Cat2metric = np.random.random(nIntCategory) # array([0.02190873, 0.9570024 , 0.34785749, 0.13852149]) # Create the "Metric" column via table lookup in Cat2metric # Whether to use apply instead of list comprehension ifUseApplyNotComprehension = True if ifUseApplyNotComprehension: # Creates error in the comment below dfObservations['Metric'] = dfObservations.apply( lambda row: Cat2metric[ row.IntCategory ] , axis=1 ) # Index error [1]: list indices must be integers or slices, # not numpy.float64 else: # No errors dfObservations['Metric'] = [ Cat2metric[i] for i in dfObservations.IntCategory ] </code>
import numpy as np
import pandas as pd
import seaborn as sns # Generates 3-tuples in original application

nObservations = 4 # Number of rows
nIntCategory = 4 # Number of categories in the categorical integer column
dfObservations = pd.DataFrame()

# Categorical data column
dfObservations['IntCategory'] = np.random.randint(nIntCategory,size=nObservations)
   # IntCategory
   #           1
   #           0
   #           3
   #           2

# Table to look up "Metric" value based on "IntCategory"
Cat2metric = np.random.random(nIntCategory)
  # array([0.02190873, 0.9570024 , 0.34785749, 0.13852149])

# Create the "Metric" column via table lookup in Cat2metric

# Whether to use apply instead of list comprehension
ifUseApplyNotComprehension = True

if ifUseApplyNotComprehension: # Creates error in the comment below

   dfObservations['Metric'] = 
   dfObservations.apply( lambda row: Cat2metric[ row.IntCategory ] , axis=1 )
      # Index error [1]: list indices must be integers or slices,
      # not numpy.float64

else: # No errors

   dfObservations['Metric'] = 
      [ Cat2metric[i] for i in dfObservations.IntCategory ]

The data is randomly generated, so it varies from trial to trial, but here is an example of what happens when I query the index row.IntCategory in the above apply loop. It returns a float!

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>row.IntCategory # Returns 3.0
</code>
<code>row.IntCategory # Returns 3.0 </code>
row.IntCategory # Returns 3.0

The apply loop can be made to work by coercing the index into an integer, i.e., int(row.IntCategory).

In this situation, why does the numerical data type change in an apply loop? It can represent a signifcant detour to track down.

The explanations I found here, here, and here all point to upcasting if the columns contain a mix of numerical types, but that’s not the situation here.

P.S. This is not a question of performance. I’ve read about avoiding apply if possible. I am seeking the most readable solution, as explained here. Also, the code above is just for troubleshooting. It doesn’t represent the actual code that led to this behaviour.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật