【问题标题】:Pandas columns of lists, create multiple columns by iterate (select) each list element of three columns as new columns and rows [duplicate]Pandas列表的列,通过迭代(选择)三列的每个列表元素作为新列和行来创建多列[重复]
【发布时间】:2021-05-04 15:15:40
【问题描述】:

我有一个五列的数据框,其中三列包含多个值的列表,它们是(“Long”,“Lat”,Time_stamp“)。请注意,所有(“Long”,“Lat”,Time_stamp“ ) 列作为对象数据类型。 我不想在一个单元格中存储多个值,而是将三列的这些值拆分为新的三列,其中包括每个列表元素,以便这些列表中的每个项目都有自己的行(在所有其他列中具有相同的值列(索引和car_id)。所以我正在寻找的输出如下:

index car_id Long Lat Time_stamp
0 8919 108.99553 34.27859 1539041301
0 8919 108.99552 34.27822 1539041304
0 8919 108.99552 34.27786 1539041307
0 8919 108.99552 34.27748 1539041310
1 19785 108.9665 34.20515 1539014039
1 19785 108.9665 34.20543 1539014042
1 19785 108.9665 34.20572 1539014046
1 19785 108.9665 34.20602 1539014049

等等.....

感谢您的帮助......

【问题讨论】:

  • 试试pd.concat([df[col].explode() for col in df.columns],axis=1)
  • 是的,感谢您的帮助,这是解决问题的好方法。非常感谢。 @anky

标签: python pandas list dataframe loops


【解决方案1】:

假设

以下代码假定只需要对固定数量的列进行规范化。

实施

import pandas as pd

df = pd.DataFrame({'car_id': [[1], [2]], 'longitudes': [[108.99553, 108.99552], [108.9665]], 'latitudes': [[34.27859, 34.27822, 34.27786], [34.20543, 34.20572]]})

print(df)

pd.DataFrame([car_id, longitude, latitude] for car_id, longitudes, latitudes in df.values for car_id in car_id for longitude in longitudes for latitude in latitudes)

【讨论】:

    【解决方案2】:

    如果列中的值在列表中,您可以使用explode 将列表中的每个值分配到自己的行中。

    请尝试

                  df2.explode('Long').explode('Lat').explode('Time_stamp')
    

    【讨论】:

      猜你喜欢
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      相关资源
      最近更新 更多