我有一个包含浮点数字符串的数据帧列,我想删除适用的尾随".0".但是,在执行操作时df["numbers"].str.replace(".0", ""),字符串"10.0"将被完全删除,而不是替换为"10".这似乎只影响数字10,100等.
MWE:
import pandas as pd
df = pd.DataFrame({"numbers": ["1.0", "10.0", "10.1", "100.0", "100.1", "99.0"]})
print df
# numbers
# 0 1.0
# 1 10.0
# 2 10.1
# 3 100.0
# 4 100.1
# 5 99.0
print df.numbers.str.replace(".0", "")
# 0 1
# 1
# 2 .1
# 3 0
# 4 0.1
# 5 99
Run Code Online (Sandbox Code Playgroud)
这是一个错误还是按预期工作?另请注意,使用此方法将"10.1"更改为".1",这很奇怪.
Dataframe.str.replace采用正则表达式,因此.匹配任何字符.你要
df.numbers.str.replace("\.0", "")
Run Code Online (Sandbox Code Playgroud)
需要$进行的比赛结束stringS和逃避.的\:
print (df.numbers.str.replace("\.0$", ""))
0 1
1 10
2 10.1
3 100
4 100.1
5 99
Name: numbers, dtype: object
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |