所以让我说我有这样的事情:〜
A
v1
v2
v3
v3
v4
我的列表是这样的:
python_list_1 = ["v1","v2"]
python_list_2 = ["v3","v4"]
现在我想在这些喜欢的东西上做点什么:
df['A'] = np.where(df['B'] in python_list_1 , "XT")
df['A'] = np.where(df['B'] in python_list_2 , "AB")
A B
v1 XT
v2 XT
v3 AB
v3 AB
v4 AB
熊猫新手的任何提示?
答案 0 :(得分:1)
将numpy.select
与isin
一起用于条件,如果某些值与两个条件都不匹配,也可以设置default
值:
print (df)
A
0 v1
1 v2
2 v3
3 v3
4 v4
5 v5
python_list_1 = ["v1","v2"]
python_list_2 = ["v3","v4"]
m1 = df['A'].isin(python_list_1)
m2 = df['A'].isin(python_list_2)
df['B'] = np.select([m1, m2], ["XT", "AB"], default=df['A'])
print (df)
A B
0 v1 XT
1 v2 XT
2 v3 AB
3 v3 AB
4 v4 AB
5 v5 v5
df['B'] = np.select([m1, m2], ["XT", "AB"], default='no match')
print (df)
A B
0 v1 XT
1 v2 XT
2 v3 AB
3 v3 AB
4 v4 AB
5 v5 no match
<{> numpy alternative
与numpy.in1d
:
m1 = np.in1d(df['A'], python_list_1)
m2 = np.in1d(df['A'], python_list_2)
df['B'] = np.select([m1,m2],[ "XT", "AB"], default='no match')
print (df)
A B
0 v1 XT
1 v2 XT
2 v3 AB
3 v3 AB
4 v4 AB
5 v5 no match
答案 1 :(得分:0)
使用apply
功能
df['B'] = df['A'].apply(lambda d: "XT" if d in l1 else ("AB" if d in l2 else "<NA>"))
答案 2 :(得分:0)
可以使用if-elif-else
创建可添加到dataframe的列表:
data = pd.DataFrame({"A" : ["v1", "v2", "v3", "v3", "v4"]})
python_list_1 = ["v1","v2"]
python_list_2 = ["v3","v4"]
outlist = []
for i in data["A"]:
if i in python_list_1:
outlist.append("XT")
elif i in python_list_2:
outlist.append("AB")
else:
outlist.append("")
data["B"] = outlist
print(data)
输出:
A B
0 v1 XT
1 v2 XT
2 v3 AB
3 v3 AB
4 v4 AB
也可以使用列表理解:
data['B'] = [ "XT" if item in python_list_1
else ("AB" if item in python_list_2 else "")
for item in data["A"]]