Pandas DataFrame:替换所有带有点逗号的值

发布于 2025-02-08 11:52:06 字数 799 浏览 4 评论 0原文

我有一个带有逗号和点的纬度列。我想 将此列转换为浮点 逗号使这不可能,所以我必须用 点。但是当我在下面尝试此功能时,这是不可能的 替换为点。我相信此功能只能替代 所有值都有逗号,但只有一些具有逗号和 因此它不进行替换。

df["LAT"].replace(",",".")

这是数据框:

     ID      LAT      LNG  
0   PLU  -12.453  -32.623 
1   OJE  -13,789  -31.933  
2   RFA  -10.157  -31.821
3   TYE  -11.253  -32.081 
4   VOL  -12,792  -32.487

预期输出:

     ID      LAT      LNG  
0   PLU  -12.453  -32.623 
1   OJE  -13.789  -31.933  
2   RFA  -10.157  -31.821
3   TYE  -11.253  -32.081 
4   VOL  -12.792  -32.487

这样我最终可以将列转换为浮点:

df["LAT"].astype(float)

有人知道我该如何替换这些逗号?

I have a latitude column written with commas and dots. And I want to
convert this column to float but there are some cells written with
commas making this not possible, so I have to replace the commas with
the points. But when I trying this function below it was not possible
to replace with points. I believe that this function only replaces if
all values have commas but there are only some that have commas and
so it doesn't do the replacement.

df["LAT"].replace(",",".")

Here is the dataframe:

     ID      LAT      LNG  
0   PLU  -12.453  -32.623 
1   OJE  -13,789  -31.933  
2   RFA  -10.157  -31.821
3   TYE  -11.253  -32.081 
4   VOL  -12,792  -32.487

Expected output:

     ID      LAT      LNG  
0   PLU  -12.453  -32.623 
1   OJE  -13.789  -31.933  
2   RFA  -10.157  -31.821
3   TYE  -11.253  -32.081 
4   VOL  -12.792  -32.487

So I can finally convert the column to a float:

df["LAT"].astype(float)

Does someone know how do I replace these commas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

森罗 2025-02-15 11:52:06

您是否将替换函数的结果分配给要更改的列?

像:

data["LAT"] = data["LAT"].str.replace(',', '.')

或者

data["LAT"].str.replace(',', '.', inplace=True)

如果您这样做,并且仍然不起作用。尝试这3个替代方案:

df.apply(lambda x: x.str.replace(',', '.'))

pd.read_csv('/your_path/your_file.csv', sep=';', decimal='.')

df.stack().str.replace(',', '.').unstack()

Are you assigning the result of the replace function back to the column you want to change?

Like:

data["LAT"] = data["LAT"].str.replace(',', '.')

or

data["LAT"].str.replace(',', '.', inplace=True)

If you are doing so, and still does not work. Try with these 3 alternatives:

df.apply(lambda x: x.str.replace(',', '.'))

pd.read_csv('/your_path/your_file.csv', sep=';', decimal='.')

df.stack().str.replace(',', '.').unstack()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文