在python中更改数组的数据类型

时间:2015-04-24 10:39:27

标签: python numpy

我通过生成一组随机数并将它们转换为int类型来创建数组。但是,我不认为下面的方式是有效的。有没有最好的方法来更改数组中的数据类型?

# standard normal distributed random numbers
c=random.randn(5,5)
c

array([[-0.37644781, -0.81347483, -0.36895952, -2.68702544, -0.96780752],
   [ 0.05293328,  1.65260753,  0.55586611, -0.5786392 ,  0.50865003],
   [ 1.25508358,  0.51783276,  2.36435212, -0.23484705, -1.20999296],
   [ 2.07552172,  0.65506648,  0.10231436, -0.26046045,  0.40148111],
   [ 0.24864496, -1.8852587 , -2.51091886,  1.01106003,  1.53118353]])

d=array([[-0.37644781, -0.81347483, -0.36895952, -2.68702544, -0.96780752],
       [ 0.05293328,  1.65260753,  0.55586611, -0.5786392 ,  0.50865003],
       [ 1.25508358,  0.51783276,  2.36435212, -0.23484705, -1.20999296],
       [ 2.07552172,  0.65506648,  0.10231436, -0.26046045,  0.40148111],
       [ 0.24864496, -1.8852587 , -2.51091886,  1.01106003,  1.53118353]],dtype=int)

d
array([[ 0,  0,  0, -2,  0],
       [ 0,  1,  0,  0,  0],
       [ 1,  0,  2,  0, -1],
       [ 2,  0,  0,  0,  0],
       [ 0, -1, -2,  1,  1]])

2 个答案:

答案 0 :(得分:7)

要么找到使用正确类型输出的方法,要么使用np.int,请参阅docs,以便更改数组的类型

在您的情况下,以下示例为您提供了类型c=random.randn(5,5).astype(np.int)

的数组
create function fn_activity_minutes(@Datetime1 DateTime,@Datetime2 DateTime)
Returns BigInt
as
Begin
    Declare 
            @Date1 Date, 
            @Date2 Date,
            @DateIndex Date,
            @minutes int,
            @lastDayMinutes int


    Set @Date1 = Convert(Date,@DateTime1)
    Set @Date2 = Convert(Date,@DateTime2)
    Set @minutes=DateDiff(minute,@DateTime1,DateAdd(Hour,22,convert(DateTime,@Date1)))
    if @minutes<0 
        Set @minutes=0

    Set @DateIndex=DateAdd(day,1,@Date1)
    While @DateIndex<@Date2
    Begin
        if DatePart(dw,@DateIndex) not in (6,7)  -- you can even check holdays here
            set @minutes=@minutes+16*60 -- 16 hours activity per day
        Set @DateIndex=DateAdd(day,1,@DateIndex)
    End
    if DatePart(dw,@DateIndex) not in (6,7)  -- you can even check holdays here
    Begin
        set @lastDayMinutes=DateDiff(minute,DateAdd(Hour,6,convert(DateTime,@Date2)),@DateTime2)
        if @lastDayMinutes>16*60
            set @lastDayMinutes=16*60
        if @Date1<>@Date2   
            set @minutes=@minutes+@lastDayMinutes
        Else
            Set @minutes=@minutes+@lastDayMinutes-16*60
    End
    return @minutes
End

答案 1 :(得分:2)

另外: library(dplyr) df %>% group_by(row.names) %>% summarise_each(sum) ,它不假定它的参数是NumPy数组。