我有一个csv文件(或数据框),如下所示:
Text Location State
A Florida, USA Florida
B NY New York
C
D abc
键值对的字典为:
stat_map = {
'FL': 'Florida',
'NY': 'New York',
'AR': 'Arkansas',
}
如何删除第3行和第4行,即使用文本C& D这样我的数据帧只包含那些我在字典中有价值的行。应删除状态为空白或具有某些不在字典值中的值的所有行。最终输出应如下所示:
Text Location State
A Florida, USA Florida
B NY New York
请帮忙。
答案 0 :(得分:0)
使用extract
+ replace
,最后按dropna
删除行:
stat_map = {
'FL': 'Florida',
'NY': 'New York',
'AR': 'Arkansas',
}
#get list from all values from keys and values of dict
L = list(stat_map.keys()) + list(stat_map.values())
print (L)
['NY', 'FL', 'AR', 'New York', 'Florida', 'Arkansas']
df['State1'] = df['Location'].str.extract('(' + '|'.join(L) + ')', expand=False)
.replace(stat_map)
df = df.dropna(subset=['State1'])
print (df)
Text Location State State1
0 A Florida, USA Florida Florida
1 B NY New York New York