【问题标题】:Difference between giving pandas a python iterable vs a pd.Series for column给 pandas 一个可迭代的 python 和一个 pd.Series 的列之间的区别
【发布时间】:2020-12-05 09:47:57
【问题描述】:

传递 Listpd.Series 类型以创建新的 dataFrame 列之间有什么区别?例如,通过反复试验,我注意到:

# (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 是添加列的“正确”方式,还是可以与其他类型互换使用?

【问题讨论】:

    标签: python pandas dataframe iterable


    【解决方案1】:

    List 此处分配给数据帧需要相同的长度

    对于pd.Series赋值,它会以索引为key匹配原来的DataFrameindex,然后在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
    

    【讨论】:

    • 为什么不默认为 RangeIndex 并用 np.nan 填充剩余部分?也许显示警告...有人知道这是否正在考虑?
    • @BEN_YO -- 好的,但是问题的其他组成部分呢(除了 NaN 填充之外的任何内容)
    • @samuelbrody1249s 检查我的第一个例子,由于索引不同,它会分配 NaN,pandas 对象分配的第一个匹配是匹配索引
    猜你喜欢
    • 2018-02-24
    • 2014-10-25
    • 2011-02-04
    • 2019-07-20
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多