【问题标题】:Create new dataframe using globals使用全局变量创建新数据框
【发布时间】:2020-12-02 12:26:36
【问题描述】:
price
               price
date    
2010-01-04  34.57282657
2010-01-04  123.900000
2010-01-04  353.6789738
2010-01-04  13.08
2010-01-04  12.45

如何为下面列表中的每个项目创建一阶差分数据框?代码需要通用。 我试过了:

listxx  = ["price"]
for x in listxx:
      globals().update({x_first_diff :x.diff().dropna()})
Expected Output:
price_first_diff 

             price_first_diff 
2010-01-04  
2010-01-04  89.33
...

【问题讨论】:

    标签: python python-3.x pandas list dataframe


    【解决方案1】:

    你快到了,只需再次使用globals 访问数据框,并格式化字符串来命名修改后的数据框:

    listxx  = ["price"]
    for x in listxx:
          globals().update({f'{x}_first_diff':globals()[x].diff().fillna('')})
    
    price_first_diff
    #              price
    #date               
    #2010-01-04         
    #2010-01-04  89.3272
    #2010-01-04  229.779
    #2010-01-04 -340.599
    #2010-01-04    -0.63
    

    您也可以尝试使用dict理解来创建新的数据框,然后更新globals

    listxx  = ["price"]
    dc={f'{x}_first_diff' :globals()[x].diff().fillna('') for x in listxx}
    globals().update(dc)
    

    【讨论】:

    • 我似乎收到了这个错误:TypeError: unsupported operand type(s) for -: 'str' and 'str'
    • 价格列好像是字符串类型,试试astype(float)
    • 谢谢。有没有办法将 first_differenced 数据框的列命名为“一阶差分量”或同一行中的内容?目前列名是volume
    • 不,我错了,不要命名变量名中带有空格的变量。 @arv 最好使用“_”作为原始字符,或者类似的字符。
    猜你喜欢
    • 2016-10-25
    • 2017-11-12
    • 2013-06-17
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多