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

Python 既然s和t的索引都相同,为什么t返回NaN作为第一个值?,python,pandas,numpy,dataframe,series,Python,Pandas,Numpy,Dataframe,Series,系列t的第一个值为NaN,但s的值为NaN。为什么这一系列的指数都一样呢 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 d

系列t的第一个值为NaN,但s的值为NaN。为什么这一系列的指数都一样呢

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

如果生成具有不同索引值的assign
系列
,则会丢失值,如第一行中的值。要正确分配,需要在
系列
数据帧
中使用相同的值

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

print (np.c_[s,t])
[[ 1  2]
 [ 2  4]
 [ 3  6]
 [ 4  8]
 [ 5 10]
 [ 6 12]]
因此,如果使用
DataFrame
构造函数被创建,那么默认的
Range\u索引从
0
开始:

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
因此,如果分配
t
,例如分配给新列,则所有工作正常,因为
df
t
中的索引相同:

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
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
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