【问题标题】:create dataframe using items in list使用列表中的项目创建数据框
【发布时间】:2020-12-03 05:27:12
【问题描述】:
price
             price       
date    
2010-01-04  30.572827     
2010-01-05  30.7725684    
2010-01-06  30.668541     
2010-01-07  30.08772827   

如何在数据框中为列表中的所有变量创建第一个差异?

listxx = ["price"]
for x in listxx:
    globals().update({f'{x}_first_diff':globals()[x].diff().dropna()})
TypeError: unsupported operand type(s) for -: 'str' and 'str'

【问题讨论】:

  • 需要转换xdtype,才能使用diff

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


【解决方案1】:

您的代码已经可以工作,但是如果您使用.diff(),则必须指定差异的来源,在您的示例中,您可能必须指定数据框中的列或使用axis 参数。

import pandas as pd
your_df = pd.DataFrame({'date': {0: '2010-01-04', 1: '2010-01-05', 2: '2010-01-06', 3: '2010-01-07'},
 'price': {0: 30.572827, 1: 30.7725684, 2: 30.668540999999998, 3: 30.08772827}})

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 2021-03-18
    • 2019-10-08
    • 2021-07-09
    • 2019-08-29
    • 2015-04-21
    • 2021-08-18
    相关资源
    最近更新 更多