gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:40 30 4
gpt4 key购买 nike

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)

关于python - Pandas iterrows 将列的类型更改为 float 。如何将其转换回原始类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42438063/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com