Pandas iterrows将列的类型更改为float.如何将其转换回原始类型?

Yuv*_*mon 1 python pandas

Pandas iterrows改变列的类型.根据这个 github问题,这是一个预期的行为.

有什么想法将pythonic和优雅的方法重新塑造成原始类型吗?请注意,我有多种列类型.

最小的例子

df = pd.DataFrame([range(5), range(5)])
df.iloc[:,1] = df.iloc[:,1].astype('float')
for row in df.iterrows():
    print row
Run Code Online (Sandbox Code Playgroud)

结果用

(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)
Run Code Online (Sandbox Code Playgroud)

请注意,df.dtypes返回列的类型,但是,我想不出使用它将行转换回该类型的优雅方式.

小智 6

请尝试使用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)
Run Code Online (Sandbox Code Playgroud)