猿问

既然 s 和 t 的索引相同,为什么 t 返回 NaN 作为第一个值?

第一个值是序列 t 的 NaN,但不是 s。为什么即使该系列具有相同的索引,为什么会这样。


import numpy as np

import pandas as pd

s = pd.Series([1,2,3,4,5,6],index= [1,2,3,4,5,6])

t = pd.Series([2,4,6,8,10,12],index= [1,2,3,4,5,6])

df = pd.DataFrame(np.c_[s,t],columns = ["MUL1","MUL2"])

df["MUL2"] =t


df



Output:


  MUL1     MUL2

0  1        NaN

1  2        2.0

2  3        4.0

3  4        6.0

4  5        8.0

5  6        10.0


慕工程0101907
浏览 130回答 1
1回答

紫衣仙女

如果分配不同的索引值,则生成缺失值,如在第一行中。为了正确分配,需要在 和 中使用相同的值。SeriesSeriesDataFrame问题是返回没有索引值的2d数组:np.c_print (np.c_[s,t])[[ 1&nbsp; 2]&nbsp;[ 2&nbsp; 4]&nbsp;[ 3&nbsp; 6]&nbsp;[ 4&nbsp; 8]&nbsp;[ 5 10]&nbsp;[ 6 12]]因此,如果使用使用构造函数创建,则默认从 以下位置开始:DataFrameRange_Index0df = pd.DataFrame(np.c_[s,t],columns = ["MUL1","MUL2"])print (df)&nbsp; &nbsp;MUL1&nbsp; MUL20&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;2 <- first 0 index1&nbsp; &nbsp; &nbsp;2&nbsp; &nbsp; &nbsp;42&nbsp; &nbsp; &nbsp;3&nbsp; &nbsp; &nbsp;63&nbsp; &nbsp; &nbsp;4&nbsp; &nbsp; &nbsp;84&nbsp; &nbsp; &nbsp;5&nbsp; &nbsp; 105&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; 12print (s)1&nbsp; &nbsp; 1 <- first 1 index2&nbsp; &nbsp; 23&nbsp; &nbsp; 34&nbsp; &nbsp; 45&nbsp; &nbsp; 56&nbsp; &nbsp; 6dtype: int64print (t)1&nbsp; &nbsp; &nbsp;2 <- first 1 index2&nbsp; &nbsp; &nbsp;43&nbsp; &nbsp; &nbsp;64&nbsp; &nbsp; &nbsp;85&nbsp; &nbsp; 106&nbsp; &nbsp; 12dtype: int64如果更改数据帧构造函数,例如通过字典:df = pd.DataFrame({"MUL1":s, "MUL2":t})print (df)&nbsp; &nbsp;MUL1&nbsp; MUL21&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;2 <- first 1 index2&nbsp; &nbsp; &nbsp;2&nbsp; &nbsp; &nbsp;43&nbsp; &nbsp; &nbsp;3&nbsp; &nbsp; &nbsp;64&nbsp; &nbsp; &nbsp;4&nbsp; &nbsp; &nbsp;85&nbsp; &nbsp; &nbsp;5&nbsp; &nbsp; 106&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; 12或者将参数添加到构造函数 by 或 Series:indexDataFramestdf = pd.DataFrame(np.c_[s,t],columns = ["MUL1","MUL2"], index=t.index)print (df)&nbsp; &nbsp;MUL1&nbsp; MUL21&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;22&nbsp; &nbsp; &nbsp;2&nbsp; &nbsp; &nbsp;43&nbsp; &nbsp; &nbsp;3&nbsp; &nbsp; &nbsp;64&nbsp; &nbsp; &nbsp;4&nbsp; &nbsp; &nbsp;85&nbsp; &nbsp; &nbsp;5&nbsp; &nbsp; 106&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; 12因此,如果赋值,例如新列都正常工作,因为在 和 中相同的索引:tdftdf["MUL3"] =tprint (df)&nbsp; &nbsp;MUL1&nbsp; MUL2&nbsp; MUL31&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;2&nbsp; &nbsp; &nbsp;22&nbsp; &nbsp; &nbsp;2&nbsp; &nbsp; &nbsp;4&nbsp; &nbsp; &nbsp;43&nbsp; &nbsp; &nbsp;3&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; &nbsp;64&nbsp; &nbsp; &nbsp;4&nbsp; &nbsp; &nbsp;8&nbsp; &nbsp; &nbsp;85&nbsp; &nbsp; &nbsp;5&nbsp; &nbsp; 10&nbsp; &nbsp; 106&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; 12&nbsp; &nbsp; 12
随时随地看视频慕课网APP

相关分类

Python
我要回答