2016-08-18 87 views
0

我有數據並將其轉換成數據幀轉化列數據框大熊貓入序列

d = [ 
    (1,70399,0.988375133622), 
    (1,33919,0.981573492596), 
    (1,62461,0.981426807114), 
    (579,1,0.983018778374), 
    (745,1,0.995580488899), 
    (834,1,0.980942505189) 
] 

df = pd.DataFrame(d, columns=['source', 'target', 'weight']) 

>>> df 
    source target weight 
0  1 70399 0.988375 
1  1 33919 0.981573 
2  1 62461 0.981427 
3  579  1 0.983019 
4  745  1 0.995580 
5  834  1 0.980943 

我需要轉換列源入序列,我一直在使用

df.source = (df.source.diff() != 0).cumsum() - 1 

嘗試,但我只是得到:

>>> df 
    source target weight 
0  0 70399 0.988375 
1  0 33919 0.981573 
2  0 62461 0.981427 
3  1  1 0.983019 
4  2  1 0.995580 
5  3  1 0.980943 

我需要變換值列的基於目標的數值源,理想的結果是:

>>> df 
    source target weight 
0  0 70399 0.988375 
1  0 33919 0.981573 
2  0 62461 0.981427 
3  1  0 0.983019 
4  2  0 0.995580 
5  3  0 0.980943 

值在源target變化匹配值,在sourcevalue 1變化爲0,所以我需要改變targetvalue 1到0太

我怎麼能這樣做?也許任何人都可以幫助我:)

謝謝:)

+0

1)沒有'value'專欄中,我假設你指的是'target'。 2)根據你的例子,我不清楚爲什麼前三個「目標」值不變。 – Alexander

+0

對不起..是沒有價值的列...值是我指的列在源或目標int ... – ihsansat

+0

因爲第一個目標不匹配源列... – ihsansat

回答

0

是這樣的?

df['source_code'] = df.source.astype('category').cat.codes 

>>> df 
    source target weight source_code 
0  1 70399 0.988375   0 
1  1 33919 0.981573   0 
2  1 62461 0.981427   0 
3  579  1 0.983019   1 
4  745  1 0.995580   2 
5  834  1 0.980943   3 
+0

不是這樣@亞歷山大,我需要根據變換值'source'更改值'target',例如我在我的問題中顯示的示例 – ihsansat

+0

您的描述與您的目標輸出不匹配。也許你可以澄清這個問題? – Alexander

+0

對不起我的錯誤,我已經澄清我的問題 – ihsansat

0

您可以使用:

#remember original values 
source_old = df.source.copy() 

df.source = (df.source.diff() != 0).cumsum() - 1 

#series for maping 
ser = pd.Series(df.source.values, index=source_old).drop_duplicates() 
print (ser) 
source 
1  0 
579 1 
745 2 
834 3 
dtype: int32 

#map where values exists 
df.target = df.target.mask(df.target.isin(ser), df.target.map(ser)).astype(int) 

print (df) 
    source target weight 
0  0 70399 0.988375 
1  0 33919 0.981573 
2  0 62461 0.981427 
3  1  0 0.983019 
4  2  0 0.995580 
5  3  0 0.980943 
+0

嗨thx @jezrael ....但如果首先我需要結合'源'和'目標'到新列調用'source_target'包括所有'源'和'目標'就像'0,1,2,3,33919,62461,70399',最後不僅是映射'source',還映射'target' – ihsansat