2017-09-21 41 views
1

我想弄明白,因爲我循環的事情,我可以添加到一個數據框的數量在某個日期從每個倉庫收到的數量列表。添加到一個數據框,因爲我走與日期時間索引

當我嘗試以下方法不起作用:

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 
+0

你有一些測試數據,像什麼'inv'是?我猜想有一個比循環更簡單的方法來轉換爲數據框。 –

+0

理解你的數據結構非常混亂。 – GiantsLoveDeathMetal

+0

@ken syme 有沒有簡單的方法來轉換數據幀,因爲我沒有總數據幀,我得到單個消息,因爲他們來了;這就是爲什麼我在這個問題中說,我們必須像這樣循環 – bpython

回答

2

說你的初始數據框看起來像這樣:

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) 
相關問題