Pandas iterrows 改变列的类型。根据this github 问题,这是预期的行为。
有没有想过用 pythonic 和优雅的方式将其转换回原始类型? 请注意,我有多种列类型。
最小的例子
df = pd.DataFrame([range(5), range(5)])
df.iloc[:,1] = df.iloc[:,1].astype('float')
for row in df.iterrows():
print row
结果
(0, 0 0.0
1 1.0
2 2.0
3 3.0
4 4.0
Name: 0, dtype: float64)
(1, 0 0.0
1 1.0
2 2.0
3 3.0
4 4.0
Name: 1, dtype: float64)
请注意,df.dtypes 返回列的类型,但是,我想不出一种优雅的方式来使用它将行转换回该类型。
请您参考如下方法:
尝试使用 df.itertuples 代替:
df = pd.DataFrame([range(5), range(5)], columns=list('abcde'))
df.iloc[:,1] = df.iloc[:,1].astype('float')
for row in df.itertuples():
print(row)
Pandas(Index=0, a=0, b=1.0, c=2, d=3, e=4)
Pandas(Index=1, a=0, b=1.0, c=2, d=3, e=4)
