Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.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,我有一个熊猫数据框,看起来像这样,其中的列如下: userid顾名思义 name是每个api事件 count是事件的频率 所以,我想要一个如下所示的数据帧: userid api_event_1 api_event_2 .... api_event_n 17 count_of_apievent1 count_of_apievent2 .... count_of_apieventn 2345 count_of_ap

我有一个熊猫数据框,看起来像这样,其中的列如下:

  • userid
    顾名思义
  • name
    是每个api事件
  • count
    是事件的频率
  • 所以,我想要一个如下所示的数据帧:

    userid    api_event_1          api_event_2          ....   api_event_n
    17        count_of_apievent1   count_of_apievent2   ....   count_of_apieventn
    2345      count_of_apievent1   count_of_apievent2   ....   count_of_apieventn
     .              .                   .                  .        .
     .              .                   .                  .        .
    
    使用DataFrame的方法:

    或者只是:

    print(df.T)
    
    使用DataFrame的方法:

    或者只是:

    print(df.T)
    
    那怎么办

    df.pivot(index='userid', columns='name', values='count_of_name')
    
    其中df是您的数据帧 (如果某些值不存在,将插入Nan。例如,如果用户X的事件A没有计数)

    要在用户没有api事件的情况下填写
    0
    而不是
    NaN
    ,可以执行以下操作:

    df.pivot(index='userid', columns='name', values='count_of_name').fillna(0)
    
    那怎么办

    df.pivot(index='userid', columns='name', values='count_of_name')
    
    其中df是您的数据帧 (如果某些值不存在,将插入Nan。例如,如果用户X的事件A没有计数)

    要在用户没有api事件的情况下填写
    0
    而不是
    NaN
    ,可以执行以下操作:

    df.pivot(index='userid', columns='name', values='count_of_name').fillna(0)
    

    这没有给我
    用户ID
    作为行:)这没有给我
    用户ID
    作为行:)完美:)我有没有办法在用户没有特定api事件的情况下将
    NaN
    转换为
    0
    呢?只需使用df.pivot(…).fillna(0):)完美:)在用户没有特定api事件的情况下,是否有任何方法可以将
    NaN
    s转换为
    0
    s?只需使用df.pivot(…).fillna(0):)