我有一个csv文件(或数据框),如下所示:
Text Location State
A Florida, USA Florida
B NY New York
C
D abc
键值对的字典为:
stat_map = {
'FL': 'Florida',
'NY': 'NewYork',
'AR': 'Arkansas',
}
如何删除第3行和第4行,即使用文本C& D这样我的数据帧只包含那些我在字典中有价值的行。 最终输出应如下所示:
Text Location State
A Florida, USA Florida
B NY New York
请帮忙。
答案 0 :(得分:1)
您正在寻找的是pandas.Series.map()
,它取代了mapper
中提供的值,此处为states_map
。
我会重复使用previous question中的数据进行说明
import pandas as pd
states_map = {
'AK': 'Alaska',
'AL': 'Alabama',
'AR': 'Arkansas',
'CA': 'California', # Enrich the dict for the current example
'NY': 'New York' # Same as above
}
>>> df
Out[]:
State
0 California, USA
1 Beverly Hills, CA
2 California
3 CA
4 NY, USA
5 USA
使用map
讨论的方法将提供
states = df['State'].str.split(', ').str[0]
>>> states
Out[]:
0 California
1 Beverly Hills
2 California
3 CA
4 NY
5 USA
Name: State, dtype: object
>>> states.map(states_map)
Out[]:
0 NaN
1 NaN
2 NaN
3 California
4 New York
5 NaN
Name: State, dtype: object
但这不是最佳选择,因为您使用split
从第1行中丢失信息,使用map
从第0行和第2行中丢失信息。
我认为可以做得更好:
split
expand=True
获取所有字词
df_parts = df.State.str.split(', ', expand=True)
>>> df_parts
Out[]:
0 1
0 California USA
1 Beverly Hills CA
2 California None
3 CA None
4 NY USA
5 USA None
mask = df_parts.isin(states_map.values())
>>> df_parts[mask]
Out[]:
0 1
0 California NaN
1 NaN NaN
2 California NaN
3 NaN NaN
4 NaN NaN
5 NaN NaN
使用~
(按位NOT)给出了掩码的反转。
df_unknown = df_parts[~mask]
>>> df_unknown
Out[]:
0 1
0 NaN USA
1 Beverly Hills CA
2 NaN None
3 CA None
4 NY USA
5 USA None
map
>>> df_unknown.apply(lambda col: col.map(states_map))
Out[]:
0 1
0 NaN NaN
1 NaN California
2 NaN NaN
3 California NaN
4 New York NaN
5 NaN NaN
并在屏蔽df_parts
df_parts [~mask] = df_unknown.apply(lambda col:col.map(states_map))
>>> df_parts
Out[]:
0 1
0 California NaN
1 NaN California
2 California NaN
3 California NaN
4 New York NaN
5 NaN NaN
>>> df_parts[0].fillna(df_parts[1]) # Fill blanks in col 1 with values in col 2
Out[]:
0 California
1 California
2 California
3 California
4 New York
5 NaN
Name: 0, dtype: object
替换原始数据框中的策展值
df['State_new'] = df_parts[0].fillna(df_parts[1])
>>> df
Out[]:
State State_new
0 California, USA California
1 Beverly Hills, CA California
2 California California
3 CA California
4 NY, USA New York
5 USA NaN
这可能不是一个完美的方法,但希望它会有所帮助。