Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将pd系列传递到数据帧?_Python_Pandas - Fatal编程技术网

Python 将pd系列传递到数据帧?

Python 将pd系列传递到数据帧?,python,pandas,Python,Pandas,我尝试了以下代码,但是new列只包含NAN值 df['new'] = pd.Series(np.repeat(1, len(df))) 有人能给我解释一下这里有什么问题吗 数据帧df的索引可能与新创建的序列不匹配。比如说, import pandas as pd import numpy as np df = pd.DataFrame({'a': [11, 22, 33, 44, 55]}, index=['r1','r2','r3','r4','r5']) df['new'] = pd.Se

我尝试了以下代码,但是
new
列只包含
NAN

df['new'] = pd.Series(np.repeat(1, len(df)))

有人能给我解释一下这里有什么问题吗

数据帧
df
的索引可能与新创建的序列不匹配。比如说,

import pandas as pd
import numpy as np
df = pd.DataFrame({'a': [11, 22, 33, 44, 55]}, index=['r1','r2','r3','r4','r5'])
df['new'] = pd.Series(np.repeat(1, len(df)))
print df
输出将是:

     a  new
r1  11  NaN
r2  22  NaN
r3  33  NaN
r4  44  NaN
r5  55  NaN
因为
pd.Series(np.repeat(1,len(df))
的索引是
int64索引([0,1,2,3,4],dtype='int64')

要防止出现这种情况,请在创建序列时指定索引参数:

df['new'] = pd.Series(np.repeat(1, len(df)), index=df.index)
或者,如果要忽略索引,则可以只传递numpy数组:

df['new'] = np.repeat(1, len(df))
不需要创建一个系列(实际上,
df['new']=1
在这种情况下就可以了)。当您需要使用索引将新列与现有数据帧对齐时,使用序列非常有用