2016-07-28 70 views
0

一個類別列合併dataframes我有兩個dataframes:按日期範圍和重複在python

DF1:

Time    A B 
1469510289000 1.5 2.4 
1469510290000 2.5 7.1 
1469510291000 2.2 6.4 
1469510292000 1.4 2.3 
1469510293000 1.6 1.8 
1469510294000 2.2 4.1 
1469510295000 1.2 0.6 

等等...

DF2:

start    end   Category 
1469510289000 1469510291000 A 
1469510291000 1469510294000 B 
1469510294000 1469510295000 A 
1469510295000 NA    C 

兩個數據幀中的時間都在曆元中。現在,我要合併的DF1 & DF2的基礎上,從DF2開始&末列,與類別。最終得到的數據框看起來像這樣(DF1):

Time    A B Category 
1469510289000 1.5 2.4 A 
1469510290000 2.5 7.1 A 
1469510291000 2.2 6.4 B 
1469510292000 1.4 2.3 B 
1469510293000 1.6 1.8 B 
1469510294000 2.2 4.1 A 
1469510295000 1.2 0.6 C 

能夠通過使用np.peicewise轉換類別爲浮動來解決它,但我怎麼能做到這一點時,我的類別爲文本或對象?請幫忙。由於

回答

1

不知道你是什麼意思「對象」,但..我認爲,如果你的意思是該類別中的字符串類型,你可以將這些數據幀轉換成列表,在列表中的字符串部分將自動成爲該形式 - >'string',並將類別標籤附加到相應的列表中,可能會得到你想要的。

像這樣

df1: 
time A B 
    1 1.5 2.4 
    2 2.5 7.1 
    3 2.2 6.4 
    4 1.4 2.3 
    5 1.6 1.8 
    6 2.2 4.1 
    7 1.2 0.6 

df2: 
start end category 
    1  3 sthtxt1 
    3  6 sthtxt2 
    6  7 sthtxt1 
    7 NA   C 

F1 = df1.values.tolist() 
F2 = df2.values.tolist() 

for item1 in F1: 
    for item2 in F2: 
     if item1[0] >= item2[0] and item1[0] < item2[1]: 
      item1.append(item2[2]) 

whatuwant=pd.DataFrame(F1) 

whatuwant: 
time A B category 
    1.0 1.5 2.4 sthtxt1 
    2.0 2.5 7.1 sthtxt1 
    3.0 2.2 6.4 sthtxt2 
    4.0 1.4 2.3 sthtxt2 
    5.0 1.6 1.8 sthtxt2 
    6.0 2.2 4.1 sthtxt1 
    7.0 1.2 0.6  C 
+0

謝謝。是的,我的意思是逐個對象。這不起作用,並在類別列中給我「無」,並帶有多個類別列。 – warwick12

+0

是df1和df2 pd.dataframe還是隻是數據文件? – Chu

+0

是的,兩者都是pd.DataFrame。我得到了輸出,但是在每個類別更改後都會生成多個列。 – warwick12

0
請問

這個幫助你嗎?

list = [] 
for time in df1['Time']: 
    category = None 
    count=-1 
    for start,end in zip(df2['start'],df2['end']): 
     count += 1 
     if (time>=start and time <= end): 
      break 
    if count != -1: 
     category = df2.ix[count]['Category'] 
    list.append(category) 
df1['Category']=list 
df1 
    A B   Time Category 
0 1.5 2.4 1469510289000  A 
1 2.5 7.1 1469510290000  A 
2 2.2 6.4 1469510291000  A 
3 1.4 2.3 1469510292000  B 
4 1.6 1.8 1469510293000  B 
5 2.2 4.1 1469510294000  B 
6 1.2 0.6 1469510295000  A