Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

pandas - Python dictionary new index returns NaN value

I am new to Python and just started learning Pandas.

I created a dictionary and want to change the index.

However, the new index shows NaN for all the values which I expect 3,5,8,-2 respectively.

I attached my code here for your reference:

states = ['place1','place2','place3','place4']

sdata = dict(a=3,b=5,c=8,d=-2)

obj4 = pd.Series(sdata, index=states)
print(obj4)

place1   NaN
place2   NaN
place3   NaN
place4   NaN
dtype: float64

Thank you so much for your help.

question from:https://stackoverflow.com/questions/65896936/python-dictionary-new-index-returns-nan-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you create series with a dictionary, the keys are taken as index and values are, well, values. So,

pd.Series(sdata)

would give you:

a    3
b    5
c    8
d   -2
dtype: int64

Now, if in addition, you pass index to pd.Series(some_dict) it is equivalent to a reindex:

pd.Series(sdata).reindex(states)

and since states doesn't contains any keys in sdata, you get a series indexed by states and contains all NaN.

If you are certain about the order, you can create the series with:

pd.Series(list(sdata.values()), index=states)

Output:

place1    3
place2    5
place3    8
place4   -2
dtype: int64

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...