List通過類型與pd.Series類型來創(chuàng)建新的 dataFrame 列之間有什么區(qū)別?例如,從反復(fù)試驗中我注意到:# (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 列表?數(shù)據(jù)框可以采用任何 python 可迭代對象還是對可以傳遞給它的內(nèi)容有限制?最后,是使用pd.Series“正確”的方式添加列,還是可以與其他類型互換使用?
1 回答

慕運維8079593
TA貢獻1876條經(jīng)驗 獲得超5個贊
List在這里分配給數(shù)據(jù)框需要相同的長度
對于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
提交
取消