gpt4 book ai didi

python - 为 Pandas 提供 python iterable 与 pd.Series for column 的区别

转载 作者:行者123 更新时间:2023-12-03 23:44:56 31 4
gpt4 key购买 nike

传递 List 之间有什么区别?对比 pd.Series键入以创建新的数据框列?例如,从反复试验中我注意到:

# (1d) We can also give it a Series, which is quite similar to giving it a List
df['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 size
d
pd.Series还有其他原因吗?与传递标准 python 列表不同?数据帧可以接受任何可迭代的 python 还是对可以传递给它的内容有限制?最后,正在使用 pd.Series添加列的“正确”方法,还是可以与其他类型互换使用?

最佳答案

List分配给这里的数据框需要相同的长度
对于 pd.Series assign ,它将使用索引作为键匹配原始 DataFrame index ,然后在 Series 中用相同的索引填充值

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

关于python - 为 Pandas 提供 python iterable 与 pd.Series for column 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63430837/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com