Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 若字符串是一个数字,则转换为浮点数,否则放入新列_Python_Pandas - Fatal编程技术网

Python 若字符串是一个数字,则转换为浮点数,否则放入新列

Python 若字符串是一个数字,则转换为浮点数,否则放入新列,python,pandas,Python,Pandas,我想取上面的数据帧,然后得到下面的数据帧。我希望CouponCode列中的所有数字都转换为浮点数或整数,如果该值不是数字,我希望将其放入新的列名couponName中(我将“nan”作为字符串输入,但当然我希望它们是“实”空值) 计划 使用pd.\u数值应用于'CouponCode'的每个单独元素。这太慢了!我为什么要这样做?因为这是我知道的确保int映射到int,float到float,以及str到str的唯一方法dtype将是object。我本可以对整个列执行pd.to\u numeric

我想取上面的数据帧,然后得到下面的数据帧。我希望CouponCode列中的所有数字都转换为浮点数或整数,如果该值不是数字,我希望将其放入新的列名couponName中(我将“nan”作为字符串输入,但当然我希望它们是“实”空值)

计划

  • 使用
    pd.\u数值
    应用于
    'CouponCode'
    的每个单独元素。这太慢了!我为什么要这样做?因为这是我知道的确保
    int
    映射到
    int
    float
    float
    ,以及
    str
    str
    的唯一方法<结果列的code>dtype
    将是
    object
    。我本可以对整个列执行
    pd.to\u numeric
    ,使用
    errors='concurve'
    ,问题是
    nan
    会将
    int
    转换为
    float
  • 使用
    .str.is_numeric
    确定哪些是字符串,并将它们移植到新列


计划

  • 使用
    pd.\u数值
    应用于
    'CouponCode'
    的每个单独元素。这太慢了!我为什么要这样做?因为这是我知道的确保
    int
    映射到
    int
    float
    float
    ,以及
    str
    str
    的唯一方法<结果列的code>dtype
    将是
    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