【问题标题】:filter pandas dataframe by cell type按细胞类型过滤熊猫数据框
【发布时间】:2018-04-20 23:42:08
【问题描述】:

我有一个从 openstreetmap 数据生成的地理数据框。我对其中一列有疑问,它返回object 的dtype,其中包含字符串和列表的混合,如下面的highway 列所示。

    access geometry                                         highway
0   NaN LINESTRING (-10817.60510122531 6680340.0880667...   footway
1   no  LINESTRING (-11843.46986863073 6678698.1663396...   footway
2   no  LINESTRING (-11843.46986863073 6678698.1663396...   [footway, steps]
3   no  LINESTRING (-11843.46986863073 6678698.1663396...   footway
4   NaN LINESTRING (-9727.497855683101 6679963.0804682...   unclassified

我正在尝试获取 highway 列的唯一值,但 unique() 函数返回 TypeError: unhashable type: 'list' 错误。我理解为什么会发生这种情况,但我不确定如何真正获得独特的价值。我正在考虑按单元格 dtype 过滤数据框,例如

dfMultitags = df[type(df['highway']) == type(list()]

但我似乎也找不到这样做的方法。欢迎任何想法。

编辑: 这个问题更多地与包含不规则列表的 pandas 列有关,Group operations on Pandas column containing lists 的解决方案在这里并不适用。答案是将列表转换为元组。在我的情况下,这会导致以下结果:

0                      (f, o, o, t, w, a, y)
1                      (f, o, o, t, w, a, y)
2                           (footway, steps)
3                      (f, o, o, t, w, a, y)
4       (u, n, c, l, a, s, s, i, f, i, e, d)
5       (u, n, c, l, a, s, s, i, f, i, e, d)
6                      (f, o, o, t, w, a, y)

理想情况下,我想将初始数据帧拆分为两个数据帧,一个包含list 类型的所有单元格,另一个包含所有str 值的单元格。

【问题讨论】:

标签: python python-3.x pandas geopandas


【解决方案1】:

您可以使用apply() 仅将列表转换为元组,而其余部分保持不变,然后调用unique():

In [15]: df = pd.DataFrame({'highway': ['footway', 'footway', ['footway', 'steps'], 'footway', 'unclassified']})

In [16]: df['highway'].apply(lambda x: tuple(x) if isinstance(x, list) else x).unique()
Out[16]: array(['footway', ('footway', 'steps'), 'unclassified'], dtype=object)

如果将tuple() 应用于整个列,它会将字符串转换为每个字符的元组。

【讨论】:

    【解决方案2】:

    您可以使用astype 转换为str,然后@chrisz 中的duplicated 数据

    df[~df.type.astype(str).duplicated(keep='first')]
    Out[75]: 
                  type
    0  [highway, road]
    1          highway
    2    [road, other]
    

    【讨论】:

      猜你喜欢
      • 2019-04-13
      • 2017-12-15
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 2015-05-28
      相关资源
      最近更新 更多