Python 若字符串是一个数字,则转换为浮点数,否则放入新列
我想取上面的数据帧,然后得到下面的数据帧。我希望CouponCode列中的所有数字都转换为浮点数或整数,如果该值不是数字,我希望将其放入新的列名couponName中(我将“nan”作为字符串输入,但当然我希望它们是“实”空值) 计划Python 若字符串是一个数字,则转换为浮点数,否则放入新列,python,pandas,Python,Pandas,我想取上面的数据帧,然后得到下面的数据帧。我希望CouponCode列中的所有数字都转换为浮点数或整数,如果该值不是数字,我希望将其放入新的列名couponName中(我将“nan”作为字符串输入,但当然我希望它们是“实”空值) 计划 使用pd.\u数值应用于'CouponCode'的每个单独元素。这太慢了!我为什么要这样做?因为这是我知道的确保int映射到int,float到float,以及str到str的唯一方法dtype将是object。我本可以对整个列执行pd.to\u numeric
- 使用
pd.\u数值
将是应用于
的每个单独元素。这太慢了!我为什么要这样做?因为这是我知道的确保'CouponCode'
映射到int
,int
到float
,以及float
到str
的唯一方法<结果列的code>dtypestr
。我本可以对整个列执行object
,使用pd.to\u numeric
,问题是errors='concurve'
会将nan
转换为int
float
- 使用
确定哪些是字符串,并将它们移植到新列.str.is_numeric
计划
- 使用
pd.\u数值
将是应用于
的每个单独元素。这太慢了!我为什么要这样做?因为这是我知道的确保'CouponCode'
映射到int
,int
到float
,以及float
到str
的唯一方法<结果列的code>dtypestr
。我本可以对整个列执行object
,使用pd.to\u numeric
,问题是errors='concurve'
会将nan
转换为int
float
- 使用
确定哪些是字符串,并将它们移植到新列.str.is_numeric
将
.str
访问器与isnumeric()一起使用
:
输出:
df['CouponName']=np.where(~df.CouponCode.str.isnumeric(),df.CouponCode,np.nan)
将
.str
访问器与isnumeric()一起使用
:
输出:
df['CouponName']=np.where(~df.CouponCode.str.isnumeric(),df.CouponCode,np.nan)
我收到以下错误:一元数的操作数类型错误:'float'。如何修复此问题?@Hound查看在进行任何其他调整之前,在dataframe上运行
~df.CouponCode.str.isnumeric()
是否会出现相同的错误。@Hound这是因为您的列中已经有一些浮点或整数。解决~df.CouponCode.astype(str).str.isnumeric()
我收到了以下错误:一元数的操作数类型错误~:“float”。如何修复此问题?@Hound查看在进行任何其他调整之前,在dataframe上运行~df.CouponCode.str.isnumeric()
是否会出现相同的错误。@Hound这是因为您的列中已经有一些浮点或整数。解决~df.CouponCode.astype(str.str.isnumeric()
df.loc[~df.CouponCode.astype(str).str.isnumeric(), 'CouponName'] = df.CouponCode
df.loc[:, 'CouponCode'] = df.CouponCode.apply(pd.to_numeric, errors='ignore')
df
CouponCode CouponName
0 1 NaN
1 2 NaN
2 3 NaN
3 Winter14 Winter14
4 5 NaN
df.to_dict('list')
{'CouponCode': [1, 2, 3, 'Winter14', 5],
'CouponName': [nan, nan, nan, 'Winter14', nan]}
df['CouponName']=np.where(~df.CouponCode.str.isnumeric(),df.CouponCode,np.nan)
CouponCode CouponName
0 1 NaN
1 2 NaN
2 3 NaN
3 Winter14 Winter14
4 5 NaN