将pandas数据框列从浮点数转换为对象,包含混合的浮点数和整数值
我在一个pandas的数据表中有一列,里面的值类型混合。有些是小数,有些是整数。由于一些规定,我需要把整数显示成没有小数点的样子。我想把这一列转换成对象类型,其中一些行是浮点数(float64),而另一些是整数(int)。
我现在的尝试是这样的:
import pandas as pd
# Sample DataFrame
data = {'A': [7.62, 5.0, 10.25, 3.0, 8.0]}
df = pd.DataFrame(data)
df['A'] = df['A'].astype('object')
# Function to format the values
def format_decimal(x):
if x % 1 == 0:
return int(x)
else:
return x
df['A'] = df['A'].apply(format_decimal)
print(df)
A |
---|
7.62 |
5.00 |
10.25 |
3.00 |
8.00 |
但是这样做没有成功,结果是5还是显示成5.0。如果需要的话,把整数当成字符串来表示也可以,我只需要去掉小数点后的0。
3 个回答
2
补充说明:我之前错误地使用了 strip
。我修改后的方案在你的原始列包含浮点数时会有效(比如5.0转换成字符串时会有一个多余的0),但@mozway提出的方案更稳妥。
你可以把这一列转换成字符串,然后替换掉结尾的 .0
:
df["A"] = df["A"].astype("string")
df["A"] = df["A"].str.replace(r".0$", "", regex=True)
A
0 7.62
1 5
2 10.25
3 3
4 8
2
如果你想保留数字,可以创建一个叫做 Series 的对象:
def try_cast_int(s):
return pd.Series([i if (i:=int(x))==x else x for x in s],
dtype=object, index=s.index)
df['out'] = try_cast_int(df['A'])
“如果有必要,可以把整数表示成字符串,只需要去掉后面的 .0 字符就行。”
把数字转换成字符串后,可以使用 str.replace
来去掉后面的 .0
:
df['out'] = df['A'].astype(str).str.replace('.0*$', '', regex=True)
举个例子:
A out
0 7.620 7.62
1 5.000 5
2 10.250 10.25
3 3.000 3
4 8.000 8
5 100.000 100
6 10.001 10.001
注意,第一个代码创建了一个包含整数和浮点数的 Series 对象,第二个代码创建的是字符串。
使用的输入:
data = {'A': [7.62, 5.0, 10.25, 3.0, 8.0, 100.0, 10.001]}
df = pd.DataFrame(data)
2
你可以结合使用 apply()
和一个叫做 lambda 的小函数,来根据条件格式化数值,像这样:
import pandas as pd
data = {'A': [7.62, 5.0, 10.25, 3.0, 8.0, 100.0, 10.001]}
df = pd.DataFrame(data)
def format_decimal(x):
if x == int(x):
return str(int(x))
else:
return str(x)
df['out'] = df['A'].apply(lambda x: format_decimal(x))
print(df)
输出结果:
A out
0 7.620 7.62
1 5.000 5
2 10.250 10.25
3 3.000 3
4 8.000 8
5 100.000 100
6 10.001 10.001