【问题标题】:Unpacking list column into a new dataframe将列表列解压缩到新数据框中
【发布时间】:2021-02-17 14:21:43
【问题描述】:

我正在尝试将 string 列(如 disttime 值解压缩(堆叠)成一个新的 df 看起来像结果 df 中所示)

df
id     hour     dow                     dist                  time
 1   (0,10)   (0,2) [(0,1), (5,7), (8,1000)]     [1.23, 5.20, 3.2]
 2. (11,15)   (3,4)               [(8,1000)]                [18.3]
 3.  (0,10)   (5,5)           [(0,1), (2,4)]            [4.5, 6.2]

达到预期结果:

id     hour   dow      dist    time
 1   (0,10)  (0,2)    (0,1)    1.23
 1   (0,10)  (0,2)    (5,7)    5.20
 1   (0,10)  (0,2) (8,1000)     3.2
 2  (11,15)  (3,4) (8,1000)    18.3
 3   (0,10)  (5,5)    (0,1)     4.5
 3   (0,10)  (5,5)    (0,1)     6.2

【问题讨论】:

    标签: python pandas string dataframe


    【解决方案1】:

    试试explode

    def yourexplode(df, col):
    
          df1 = pd.concat([ df[x].explode() for x in col], axis=1)
          return df1.join(df.drop(col, 1), how='left')
    
    newdf = yourexplode(df,['dist','time'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 2020-03-12
      • 2018-07-04
      • 1970-01-01
      • 2021-05-19
      相关资源
      最近更新 更多