【问题标题】:add to a dataframe as I go with datetime index在使用日期时间索引时添加到数据框
【发布时间】:2017-09-21 12:19:15
【问题描述】:

我正在尝试获取它,以便当我遍历一个东西列表时,我可以将某个日期从每个仓库收到的数量添加到数据框中。

当我尝试以下方法时它不起作用:

if inv['prod'] not in self.inventory.columns:
    ## add row in
    self.inventory[inv['prod']] = 0
    idx = inv['time_stamp'].split(' ')[0]
    if idx not in self.inventory.index:
        self.inventory[idx, :] = 0

    self.inventory[idx, inv['prod']] += inv['qty'] 

我基本上需要它来添加基于每个产品的列,然后是它的到达/销售日期。我知道这不是很pythonic,但只是假设我不提前知道日期或产品。

数据框最终将如下所示:

Date         InventoryA       InventoryB
2017-01-01       10              NaN
2017-01-02       NaN             NaN
2017-01-03       NaN              5
2017-01-04       NaN              5
2017-01-05       -5              NaN
2017-01-06       NaN             -10
2017-01-07       15              NaN
2017-01-08       NaN             NaN
2017-01-09      -20              NaN

【问题讨论】:

  • 你有一些测试数据,比如inv 是什么?我猜想有一种比循环更简单的方法可以转换为数据帧。
  • 理解你的数据结构非常混乱。
  • @ken syme 没有更简单的方法来转换数据帧,因为我没有总数据帧,我会收到单独的消息;这就是为什么我在问题中说我们必须这样循环
  • @bpython 你能举一个你得到的inv“消息”的例子吗?
  • ['InventoryA', 10]

标签: python pandas dataframe insert


【解决方案1】:

假设您的初始数据框如下所示:

data = {'InventoryA': [10, np.nan, -5]}
df = pd.DataFrame(data, index=pd.to_datetime(['2017-01-01', '2017-01-03', '2017-01-05']))

现在你想添加一个新值(不确定你想要它的形式,但它在数据框中):

new_vals = pd.DataFrame({'InventoryB': 10}, index=pd.to_datetime(['2017-01-02']))

# Add new column if it doesn't exist.
if new_vals.columns.values not in df.columns.values:
    df[new_vals.columns.values[0]] = np.nan

# Add new row if it doesn't exist or add value if it does.
if new_vals.index not in df.index: 
    df = df.append(new_vals)
else: df.loc[new_vals.index, new_vals.columns] += new_vals

# Sort by date
df = df.sort_index(axis=0)

【讨论】:

    猜你喜欢
    • 2021-03-12
    • 2021-01-19
    • 2017-10-04
    • 2018-08-24
    • 2019-09-23
    • 2021-01-16
    • 2021-11-29
    • 2017-11-23
    • 1970-01-01
    相关资源
    最近更新 更多