使用Plotly绘制东京租金折线图时Y轴排序异常如何修复
问题修复方案
问题根源
Rent(Local Currency)列数据带有千位分隔符逗号,pandas读取CSV时默认将该列识别为字符串类型,Plotly绘图时会按照字符串字典序排序Y轴,而非数值大小,因此出现排序混乱。
修复方法
两种可选方案,任选其一即可:
方案1:读取CSV时指定千位分隔符
在pd.read_csv中添加thousands=','参数,pandas会自动解析带千位分隔符的数值:
import numpy as np import pandas as pd import plotly.express as px df = pd.read_csv('Tokyo rent (One Bedroom apartment in the city centre).csv', thousands=',') fig = px.line(df, x = 'Date 2.0', y = 'Rent(Local Currency)', title='Tokyo Rent Price (Yen)') fig.show()
方案2:读取数据后手动转换列类型
如果不需要修改全局读取配置,可以单独处理目标列:
# 先移除列中所有逗号,再转换为浮点型 df['Rent(Local Currency)'] = df['Rent(Local Currency)'].str.replace(',', '').astype(float) # 转换完成后绘图即可 fig = px.line(df, x = 'Date 2.0', y = 'Rent(Local Currency)', title='Tokyo Rent Price (Yen)') fig.show()
验证方法
你可以执行print(df['Rent(Local Currency)'].dtype)查看列类型:
- 处理前输出为
object(字符串类型) - 处理后输出为
float64(数值类型),即代表转换成功,Y轴排序会自动恢复正常。
内容的提问来源于stack exchange,提问作者pfft khaganate
相关产品推荐
相关产品推荐

