Python 无法使用series设置列值,请将所有内容改为np.nan

Python 无法使用series设置列值,请将所有内容改为np.nan,python,pandas,dataframe,indexing,nan,Python,Pandas,Dataframe,Indexing,Nan,我有以下熊猫(pd)数据帧: > df = pd.DataFrame({'x':[1,2,3], 'y':[4,5,6], 'z':[7,8,9]}, index=['one', 'two', 'three']) > df x y z one 1 4 7 two 2 5 8 three 3 6 9 和一系列: s = pd.Series([99,99,99]) 当我尝试将b中的这些值分配给df中的某列时,我没有得到任何错误,但该列中的所

我有以下熊猫(
pd
)数据帧:

> df = pd.DataFrame({'x':[1,2,3], 'y':[4,5,6], 'z':[7,8,9]}, index=['one', 'two', 'three'])
> df
       x  y  z
one    1  4  7
two    2  5  8
three  3  6  9
和一系列:

s = pd.Series([99,99,99])
当我尝试将
b
中的这些值分配给
df
中的某列时,我没有得到任何错误,但该列中的所有值都设置为
nan

> df['y'] = s
> df
       x   y  z
one    1 NaN  7
two    2 NaN  8
three  3 NaN  9

在使用此赋值技术之前,我已经多次设置了数据框列值,为什么不再有效?

问题在于
数据框中的索引值与
系列中的索引值不匹配。
默认情况下,任何pandas索引都具有从
0
开始计算的整数值,因此如果不修改它们,并且列和
系列的长度匹配,则不会出现问题

但是,您修改了
df
的索引值,并将其设置为
['one'、'two'、'three']
。 您应该确保:

  • 系列
    使用与
    数据帧相同的索引

    > s = pd.Series({'one': 99, 'two': 99, 'three': 99})
    > df['y'] = s
    
  • 或者,您可以只使用
    s
    中的(无索引)值:

    > df['y'] = s.values
    
获得:

> df
       x   y  z
one    1  99  7
two    2  99  8
three  3  99  9
ICCU:

另一种方法。请尝试df.assign

df.assign(y=s.values)