python - 来自两列 DataFrame 的 Pandas Series 产生一系列 NaN
问题描述
state_codes = pd.read_csv('name-abbr.csv', header=None)
state_codes.columns = ['State', 'Code']
codes = state_codes['Code']
states = pd.Series(state_codes['State'], index=state_codes['Code'])
name-abbr.csv
是一个双列 CSV 文件,第一列是美国州名,第二列是邮政编码:第一行是“Alabama”和“AL”,第二行是“Alaska”和“AK”,依此类推。
上面的代码正确设置了索引,但是 Series 是 all NaN
。如果我不设置索引,则状态名称会正确显示。但我两者都想要。
我也试过这条线:
states = pd.Series(state_codes.iloc[:,0], index=state_codes.iloc[:,1])
结果相同。我怎样才能让它工作?
解决方案
这里是对齐的原因,这意味着pandas
尝试将索引state_codes['State'].index
与新索引匹配,state_codes['Code']
并且因为不同的输出在输出中得到缺失值,为了防止有必要将 Series 转换为 numpy 数组:
states = pd.Series(state_codes['State'].to_numpy(), index=state_codes['Code'])
或者您可以使用DataFrame.set_index
:
states = state_codes.set_index('Code')['State']
推荐阅读
- vue.js - Vue vuex缩短mapState
- sql - 随机字符串函数并不总是返回相同的长度
- ruby-on-rails - Rails v6.0.0rc1 form_for 在rails控制台中工作但不在应用程序中
- javascript - Javascript 函数 - 破译有关基本函数的文档
- haproxy - HAProxy Maps 基于路径,如果主机匹配
- bluetooth-lowenergy - 为什么在使用低功耗蓝牙时必须停止蓝牙?
- python - 如何修改 CheckButtons 中的填充?
- javascript - 如何将输入值获取到 GET API 响应?
- recursion - J语言中的递归
- sql - 如何提取一个表中存在的不同 ID 而不是另一个表