为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕工程0101907 2022-09-13 15:13:50
第一个值是序列 t 的 NaN,但不是 s。为什么即使该系列具有相同的索引,为什么会这样。import numpy as npimport pandas as pds = 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"] =tdfOutput:  MUL1     MUL20  1        NaN1  2        2.02  3        4.03  4        6.04  5        8.05  6        10.0
查看完整描述

1 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

如果分配不同的索引值,则生成缺失值,如在第一行中。为了正确分配,需要在 和 中使用相同的值。SeriesSeriesDataFrame


问题是返回没有索引值的2d数组:np.c_


print (np.c_[s,t])

[[ 1  2]

 [ 2  4]

 [ 3  6]

 [ 4  8]

 [ 5 10]

 [ 6 12]]

因此,如果使用使用构造函数创建,则默认从 以下位置开始:DataFrameRange_Index0


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

print (df)

   MUL1  MUL2

0     1     2 <- first 0 index

1     2     4

2     3     6

3     4     8

4     5    10

5     6    12


print (s)

1    1 <- first 1 index

2    2

3    3

4    4

5    5

6    6

dtype: int64


print (t)

1     2 <- first 1 index

2     4

3     6

4     8

5    10

6    12

dtype: int64

如果更改数据帧构造函数,例如通过字典:


df = pd.DataFrame({"MUL1":s, "MUL2":t})

print (df)

   MUL1  MUL2

1     1     2 <- first 1 index

2     2     4

3     3     6

4     4     8

5     5    10

6     6    12

或者将参数添加到构造函数 by 或 Series:indexDataFramest


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

print (df)

   MUL1  MUL2

1     1     2

2     2     4

3     3     6

4     4     8

5     5    10

6     6    12

因此,如果赋值,例如新列都正常工作,因为在 和 中相同的索引:tdft


df["MUL3"] =t

print (df)

   MUL1  MUL2  MUL3

1     1     2     2

2     2     4     4

3     3     6     6

4     4     8     8

5     5    10    10

6     6    12    12


查看完整回答
反对 回复 2022-09-13
  • 1 回答
  • 0 关注
  • 129 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号