List通过类型与pd.Series类型来创建新的 dataFrame 列之间有什么区别?例如,从反复试验中我注意到:# (1d) We can also give it a Series, which is quite similar to giving it a Listdf['cost1'] = pd.Series([random.choice([1.99,2.99,3.99]) for i in range(len(df))])df['cost2'] = [random.choice([1.99,2.99,3.99]) for i in range(len(df))]df['cost3'] = pd.Series([1,2,3]) # <== will pad length with `NaN`df['cost4'] = [1,2,3] # <== this one will fail because not the same sized是否有任何其他原因pd.Series不同于传递标准 python 列表?数据框可以采用任何 python 可迭代对象还是对可以传递给它的内容有限制?最后,是使用pd.Series“正确”的方式添加列,还是可以与其他类型互换使用?
1 回答
慕运维8079593
TA贡献1876条经验 获得超5个赞
List在这里分配给数据框需要相同的长度
对于pd.Seriesassign,它会使用index作为key去匹配original DataFrame index,然后用相同的index填充valueSeries
df=pd.DataFrame([1,2,3],index=[9,8,7])
df['New']=pd.Series([1,2,3])
# the default index is range index , which is from 0 to n
# since the dataframe index dose not match the series, then will return NaN
df
Out[88]:
0 New
9 1 NaN
8 2 NaN
7 3 NaN
具有匹配索引的不同长度
df['New']=pd.Series([1,2],index=[9,8])
df
Out[90]:
0 New
9 1 1.0
8 2 2.0
7 3 NaN
添加回答
举报
0/150
提交
取消