【问题标题】:Python Pandas - Find rows where element is in row's arrayPython Pandas - 查找元素在行数组中的行
【发布时间】:2020-06-01 02:42:16
【问题描述】:

我想查找列的列表值中存在某个值的所有行。

假设我有一个这样的dataframe 设置:

|  placeID |                             users | 
------------------------------------------------
|    134986|   [U1030, U1017, U1123, U1044...] |
|    133986|   [U1034, U1011, U1133, U1044...] |
|    134886|   [U1031, U1015, U1133, U1044...] |
|    134976|   [U1130, U1016, U1133, U1044...] |

如何获取用户列中存在'U1030' 的所有行?

或者...真正的问题是我不应该像这样排列我的数据,而是应该分解该列以便为每个用户设置一行?

解决这个问题的正确方法是什么?

【问题讨论】:

  • 您尝试了哪些代码,其结果与预期输出有何不同?

标签: python pandas dataframe machine-learning data-science


【解决方案1】:

在我看来,您存储数据的方式很好。您无需更改存储数据的格式。

试试这个:

df1 = df[df['users'].str.contains("U1030")]

print(df1)

这将为您提供包含df 格式的指定用户的所有行。

【讨论】:

  • @Paul 这有帮助吗?
  • 不幸的是没有,当我尝试它时它给了我一个奇怪的键错误。我确实解决了我的问题,答案将立即发布。
【解决方案2】:

当列中的值是列表时,当您想检查列中是否存在值时,使用map 函数会很有帮助。

像下面这样实现它,使用 lambda 内联函数,存储在 'users' 列中的值列表映射到值 u,并将 userID 与它进行比较......

当您查看下面的代码时,答案真的很简单:


# user_filter filters the dataframe to all the rows where
# 'userID' is NOT in the 'users' column (the value of which
# is a list type)
user_filter = df['users'].map(lambda u: userID not in u)

# cuisine_filter filters the dataframe to only the rows
# where 'cuisine' exists in the 'cuisines' column (the value
# of which is a list type)
cuisine_filter = df['cuisines'].map(lambda c: cuisine in c)

# Display the result, filtering by the weight assigned
df[user_filter & cuisine_filter]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 2018-03-14
    • 2015-01-31
    • 2022-06-29
    • 2022-01-09
    • 2022-11-18
    相关资源
    最近更新 更多