我有一个pandas数据框,它的列数如下。Column_1是字符串文本,不是整数或十进制。有几行也有字符串值,比如名字(参考第6行)。
S.No. Column_1
1 256
2 1
3 $300.54672
4 756
5 $292.34333
6 Andrew
我想将column_1中的所有数值转换为numbersint,除了美元数值和带有名称的行。我要求保留美元符号,但金额应该在小数点后四舍五入到2位数。
预期的输出。
S.No. Column_1
1 256
2 1
3 $300.55
4 756
5 $292.34
6 Andrew
我使用 pd.to_numeric() 将整个列转换为数字,并使用 errors='coerce',但金额值变成了空白(或)空,因为这是一个错误。
如果有任何建议帮助,我将非常感激。谢谢你的帮助。
筛选值以 $
由 Series.str.startswith
移除 $
由 Series.str.strip
转换为数字、四舍五入、转换为字符串和前缀。$
:
m = df['Column_1'].str.startswith('$', na=False)
s = '$' + df.loc[m, 'Column_1'].str.strip('$').astype(float).round(2).astype(str)
或。
s = df.loc[m, 'Column_1'].str.strip('$').astype(float).round(2).astype(str).radd('$')
df.loc[m, 'Column_1'] = s
print (df)
S.No. Column_1
0 1 256
1 2 1
2 3 $300.55
3 4 756
4 5 $292.34
最后,如果需要将非匹配值转换为数值,但得到混合数据类型--字符串与 $
和数字,不含 $
:
df.loc[~m, 'Column_1'] = pd.to_numeric(df.loc[~m, 'Column_1'])
print (df)
S.No. Column_1
0 1 256
1 2 1
2 3 $300.54672
3 4 756
4 5 $292.34333
print (df['Column_1'].apply(type))
0 <class 'int'>
1 <class 'int'>
2 <class 'str'>
3 <class 'int'>
4 <class 'str'>
Name: Column_1, dtype: object
对最后一段进行编辑。在此可能增加: errors='coerce'
用于将非数值转换为缺失值,然后用原始值替换。
df.loc[~m, 'Column_1'] = pd.to_numeric(df.loc[~m, 'Column_1'], errors='coerce').fillna(df['Column_1'])
print (df)
S.No. Column_1
0 1 256
1 2 1
2 3 $300.55
3 4 756
4 5 $292.34
5 6 Andrew
print (df['Column_1'].apply(type))
0 <class 'float'>
1 <class 'float'>
2 <class 'str'>
3 <class 'float'>
4 <class 'str'>
5 <class 'str'>
Name: Column_1, dtype: object