我正在可能的列中搜索值。我能找到有火柴的地方。然后,我的挑战变成了如何选择非空列。
import pandas as pd
import numpy as np
data = {"Search1":["one_two","two_ten", "five_ten"],
"Search2":["three_four","one_four","two_twelve"],
"FindMe":["three","one","nine"],
"FindMe2":["five","two","nine"]}
df =pd.DataFrame(data)
df["Found1"] = np.where(df.apply(lambda x: str(x.FindMe) in str(x.Search1), axis =1) ==1, df.Search1,
np.where(df.apply(lambda x: str(x.FindMe) in str(x.Search2), axis =1) ==1, df.Search2,""))
df["Found2"] = np.where(df.apply(lambda x: str(x.FindMe2) in str(x.Search1), axis =1) ==1, df.Search1,
np.where(df.apply(lambda x: str(x.FindMe2) in str(x.Search2), axis =1) ==1, df.Search2,""))
#sum of founds
df["Want_Sum"] = [1,2,0]
#return value where not blank
#second is blank because there are two options in Found 1 and Found2
df["Value_of_Found"] = ["three_four", "", ""]
print(df)
我想对Found1和Found2的非空列求和,当这等于1时,取填充的列。
我发布了另一个关于如何编写Found1代码的问题。
如果我理解您正在尝试的内容,那么您可以使用嵌套的np.where()
:
np.where((df['Found1'].str.len() > 0) ^ (df['Found2'].str.len() > 0),
np.where((df['Found1'].str.len() > 0), df['Found1'], df['Found2'] ), '' )
结果:
array(['three_four', '', ''], dtype=object)
您可以将分配给列
df['Filled'] = np.where(...)
以下是有关其工作原理的更多详细信息
CCD_ 2是这个答案的基本组成部分。它根据条件返回两个不同值中的一个。如果条件为true,则返回第一个值;如果条件为false,则返回第二个值。
np.where(condition, value-if-true, value-if-false)
这个答案包含一个嵌套的np.where()
语句。如果上面的值为true,则另一个np.where()
将替换该值。
np.where(condition, np.where(condition, value-if-true, value-if-false), value-if-false)
第一个条件使用exclusive或logic检查Found1和Found2的长度是否不同。
(df['Found1'].str.len() > 0) ^ (df['Found2'].str.len() > 0)
如果它们不同,那么这意味着我们需要选择len>0通过嵌套的np.where()
:
np.where((df['Found1'].str.len() > 0), df['Found1'], df['Found2'] )
这里有一个可以轻松扩展到多列的解决方案。使用filter
和regex='Foundd'
来选择数据帧中找到的所有列。沿列检查不等于(ne
(和sum
以获得Want_Sum列。对于Value_of_Found列,仅当总和为1时,则可以执行np.where
,如果Want_sum等于1,则沿列获取max
Found-else空字符串。
df['Want_Sum'] = df.filter(regex='Foundd').ne('').sum(axis=1)
df["Value_of_Found"] = np.where(df['Want_Sum'].eq(1),
df.filter(regex='Foundd').max(axis=1),
'')
print(df)
Search1 Search2 FindMe FindMe2 Found1 Found2 Want_Sum
0 one_two three_four three five three_four 1
1 two_ten one_four one two one_four two_ten 2
2 five_ten two_twelve nine nine 0
Value_of_Found
0 three_four
1
2