考虑一个Pandas中的数据框,其中许多列中的一列的数据中有两个小数。 像
13.343.00
12.345.00
98.765.00
如何获得一个新列(浮点数),其中的值仅以1个十进制格式存储,以剥离14.234(.00)
的最后一部分。
所需的输出应为新列,例如
13.343
12.345
98.765
答案 0 :(得分:4)
如果第二个句点之后的数字不总是为0(也不总是为2),则以下代码会更可靠:
df["col"] = df["col"].str.extract("(.+)\.[0-9]+").astype(float)
答案 1 :(得分:3)
您可以使用:
print(df)
col
0 13.343.00
1 12.345.00
2 98.765.00
df.col=df.col.str.rstrip('.00')
print(df)
col
0 13.343
1 12.345
2 98.765
如果愿意,可以将其转换回float
注意:如果全为0,则不应该使用此示例:astype(float)
而是使用第二种解决方案。
如果第二位小数不总是0,请使用:
00.000.00
答案 2 :(得分:3)
使用:
#remove last 3 values
df['col'] = df['col'].str[:-3].astype(float)
或者:
#get values before last .
df['col'] = df['col'].str.rsplit('.', 1).str[0].astype(float)
或者:
#one or zero integer \d* \. and integer \d+ pattern
df["col"] = df["col"].str.extract("(\d*\.\d+)").astype(float)