简体   繁体   English

如果列表中的列中的单词在新列中添加Y标志,则为python熊猫

[英]python Pandas if word in column in list add Y flag in new column

I can't figure out if statements in python pandas. 我不知道python pandas中的语句。

I have a dataframe df 我有一个数据框df

Category | Count
A           45756
B           5857
C           57876

I create a list and then use it as a hierarchy 我创建一个列表,然后将其用作层次结构

list_s = {'A':'Y',
'B':'Y'}
df['Flag'] = df['Category'].replace(list_s)

but I get 但我明白了

Category | Count   | Flag 
A           45756     Y
B           5857      Y
C           57876     C

instead of 代替

Category | Count   | Flag 
A           45756     Y
B           5857      Y
C           57876     

Thank You! 谢谢!

Use map with a lambda function in which you utilize dictionary's get method where you can pass a default value maplambda函数一起使用,在该函数中,您可以利用字典的get方法来传递默认值

list_s = {'A':'Y', 'B':'Y'}
df['Flag'] = df['Category'].map(lambda x: list_s.get(x, ''))

print(df)

  Category  Count Flag
0        A  45756    Y
1        B   5857    Y
2        C  57876    

IIUC you can do it this way: IIUC您可以通过以下方式进行操作:

In [8]: df['Flag'] = df['Category'].map(list_s).fillna('')

In [9]: df
Out[9]:
  Category  Count Flag
0        A  45756    Y
1        B   5857    Y
2        C  57876

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM