首页 > 解决方案 > 来自两列 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])

结果相同。我怎样才能让它工作?

标签: pythonpandas

解决方案


这里是对齐的原因,这意味着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']

推荐阅读