簡體   English   中英

如何在 pandas df col 中使用嵌套列表中的元素作為 if 語句條件

[英]how to use elements in a nested list in pandas df col as if statement conditions

這是一個很奇怪的問題,我什至不知道如何表達它。

df看起來像這樣:

col4
['df['col1'] == 10]', ['df['col2'] == 'cat']']
['df['col1'] == 20]', ['df['col3'] == 'some string']']

df1看起來像這樣:

col1    col2    col3
10      cat     some string
20      dog     some string

我的目標是將df.col4中的元素用作針對另一個 df ( df1 ) 的 if 語句中的條件。

df1.new_col 的df1.new_col我的目標是:

col1    col2    col3          new_col
10      cat     some string   yes
20      dog     some string   yes
30      pet     some string   no

我感謝大家的幫助。

您應該查看query() 它允許你做類似的事情

df1.query("col1 == 10 & col3 == 'some string'")

在這種情況下會產生

   col1 col2         col3
0    10  cat  some string

並使用命中數來填充new_col列。 但這需要您將df.col4中的條件重新格式化為與query()兼容的內容。 另外我不明白為什么要將這些條件作為嵌套列表保留在 dataframe 列中,這對我來說看起來非常不切實際。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM