Skip to main content
 首页 » 编程设计

python之字符串问题/在 pandas 数据框中选择所有 > 8000 的值

2025年05月04日21lovecherry

我想在 pandas 数据框中选择所有大于 8000 的值。

new_df = df.loc[df['GM'] > 8000]

但是,它不起作用。我认为问题在于,该值来自 Excel 文件,并且该数字被解释为字符串,例如“1.111,52”。你知道我如何将这样的字符串转换为 float/int 以便正确比较它吗?

请您参考如下方法:

摘自 pd.read_excel 的文档:

Thousands separator for parsing string columns to numeric. Note that this parameter is only necessary for columns stored as TEXT in Excel, any numeric columns will automatically be parsed, regardless of display format.

这意味着 pandas 检查存储在 excel 中的格式的类型。如果这是 Excel 中的 numeric,则转换应该是正确的。如果您的列是 string,请尝试使用:

df = pd.read_excel('filename.xlsx', thousands='.') 

如果你有一个 csv 文件,你可以通过指定 thousands + decimal 字符来解决这个问题:

df = pd.read_csv('filename.csv', thousands='.', decimal=',')