2017-08-11 84 views
0
BK = pd.DataFrame([], columns=(['Datetime','X','Y','Z'])) 

Time = 08082012 
A1 = 28.455 
B1 = 14.675 
C1 = 124.674 

# Assign first four values under 'Datetime','X','Y','Z' 
# Assign next values in a row under the first values 

Time = 09082012 
A1 = 28.923 
B1 = 14.122 
C1 = 123.158 

# Assign next values in a row under the second values 
Time = 10082012 
A1 = 27.923 
B1 = 15.122 
C1 = 127.158 

我們假設行數可以是無限的。 如何將變量分配到行之後的數據幀行中? 如果我一直覆蓋變量,是否會出現異常?如何連續分配一個變量到一個數據幀行(熊貓)?

回答

0
BK = pd.DataFrame([], columns=(['Datetime','X','Y','Z'])) 
rows = [[Time],[A1],[B1],[C1]] 
BK.loc[len(BK)] = rows 

=

BK.loc[len(BK)]= [[Time],[A1],[B1],[C1]] 

易並且很快,特別是如果使用循環有些種類。

+0

你確定嗎?在我看來,如果創建列表和數據框構造函數更快。你可以添加一些時間嗎? – jezrael

+0

嗨jazrael,你只需要創建數據幀一旦它開始或之後,然後它將變量添加到行。在我寫這篇評論的時候,可能還有可能將數據直接導向數據框。我必須弄清楚。 – Bondeaux

+0

我只認爲最好的解決方案是創建列表和數據框,因爲它是快速,簡單和推薦的(就像Dov Grobgeld在他的回答中所說)。所以我很驚訝,你認爲創建行數據到數據框很快 - 在我看來不是。還是缺少什​​麼? – jezrael

0

我認爲最好是建立嵌套列表(或元組的列表),然後分配給DataFrame構造:

#one possible solution for create nested list, try modify for real data 
L = [x for x in function_generate_rows()] 

#another possible solution 
L = [] 
for x in range(5): 
    row = function_generate_rows(x) 
    L.append(row) 

print (L) 
[[08082012,28.455,14.675,124.674],[09082012,28.923,14.122,123.158], ...] 

df = pd.DataFrame(L, columns = ['Datetime','X','Y','Z']) 
0

下也適用,但它可能是慢於先創建一個列表,並在最後把它變成一個數據幀(這是我平時做):

import pandas as pd 

BK = pd.DataFrame([], columns=(['Datetime','X','Y','Z'])) 

Time = 8082012 
A1 = 28.455 
B1 = 14.675 
C1 = 124.674 

BK=BK.append({'Datetime':Time,'X':A1,'Y':B1,'Z':C1}, ignore_index=True) 
# Assign first four values under 'Datetime','X','Y','Z' 
# Assign next values in a row under the first values 

Time = 9082012 
A1 = 28.923 
B1 = 14.122 
C1 = 123.158 
BK=BK.append({'Datetime':Time,'X':A1,'Y':B1,'Z':C1}, ignore_index=True) 

# Assign next values in a row under the second values 
Time = 10082012 
A1 = 27.923 
B1 = 15.122 
C1 = 127.158 
BK=BK.append({'Datetime':Time,'X':A1,'Y':B1,'Z':C1}, ignore_index=True) 

print BK 
相關問題