[英]how to use elements in a nested list in pandas df col as if statement conditions
It's such a weird question, I don't even know how to phrase it.这是一个很奇怪的问题,我什至不知道如何表达它。
df
looks like this: df
看起来像这样:
col4
['df['col1'] == 10]', ['df['col2'] == 'cat']']
['df['col1'] == 20]', ['df['col3'] == 'some string']']
df1
looks like this: df1
看起来像这样:
col1 col2 col3
10 cat some string
20 dog some string
my goal is to use the elements in df.col4
as conditions in an if statement against another df ( df1
).我的目标是将
df.col4
中的元素用作针对另一个 df ( df1
) 的 if 语句中的条件。
output for df1.new_col
i'm aiming for is: 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
I appreciate all y'alls help.我感谢大家的帮助。
You should look into query() .您应该查看query() 。 It allows you to do something like
它允许你做类似的事情
df1.query("col1 == 10 & col3 == 'some string'")
which in this case would yield在这种情况下会产生
col1 col2 col3
0 10 cat some string
and use the number of hits to populate the new_col
column.并使用命中数来填充
new_col
列。 But it requires you to reformat your conditions in df.col4
to something that is compatible with query()
.但这需要您将
df.col4
中的条件重新格式化为与query()
兼容的内容。 Also I don't understand why you would keep those conditions as nested lists in a dataframe column, it looks wildly impractical to me.另外我不明白为什么要将这些条件作为嵌套列表保留在 dataframe 列中,这对我来说看起来非常不切实际。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.