2017-07-18 76 views
1

參照其他列的值在大熊貓的數據框中添加一個新的專欄中,我有熊貓我怎樣才能在巨蟒

df 
index | ref | 1 | 2 | 3 | 4 | 5 | 
1  | 1 | -3 | -2 | -9 | 0 | -2 | 
2  | 3 | -1 | -2 | -5 | 3 | -5 | 
3  | 5 | -4 | -7 | -4 | 2 | -1 | 
4  | 4 | -2 | -4 | -2 | -1 | -9 | 
5  | 1 | -2 | -3 | -1 | -3 | -3 | 

而且我想參照使「新」一欄的數據框下方「參考」列的值如下,

df 
index | ref | 1 | 2 | 3 | 4 | 5 | new | 
1  | 1 | -3 | -2 | -9 | 0 | -2 | -3 | 
2  | 3 | -1 | -2 | -5 | 3 | -5 | -5 | 
3  | 5 | -4 | -7 | -4 | 2 | -1 | -1 | 
4  | 4 | -2 | -4 | -2 | -1 | -9 | -1 | 
5  | 1 | -2 | -3 | -1 | -3 | -3 | -2 | 

我曾嘗試如下,但由於缺乏內存,我失敗了。 (東西在代碼循環)

df['new'] = df[df['ref']] 

你能爲我的建議嗎?

回答

0

您可以使用以下語法。這裏參數可以爲例如是如在多重表達由3

df['new'] = df['ref'] * <parameter> 

T['new'] = T['column0'] * 3 
1

需要DataFrame.lookup,但需要相同類型的列和值的ref柱:

​​
#values are strings 
print (df['ref'].tolist()) 
['1', '3', '5', '4'] 
print (df.columns.tolist()) 
['ref', '1', '2', '3', '4', '5'] 

df['new '] = df.lookup(df.index, df['ref']) 
print (df) 
     ref 1 2 3 4 5 new 
index       
1  1 -3 -2 -9 0 -2 -3 
2  3 -1 -2 -5 3 -5 -5 
3  5 -4 -7 -4 2 -1 -1 
4  4 -2 -4 -2 -1 -9 -1 

編輯:

如果在列名的值是字符串和值在ref的整數的轉換添加astype

print (df['ref'].tolist()) 
[1, 3, 5, 4] 
print (df.columns.tolist()) 
['ref', '1', '2', '3', '4', '5'] 

df['new '] = df.lookup(df.index, df['ref'].astype(str)) 
print (df) 
     ref 1 2 3 4 5 new 
index       
1  1 -3 -2 -9 0 -2 -3 
2  3 -1 -2 -5 3 -5 -5 
3  5 -4 -7 -4 2 -1 -1 
4  4 -2 -4 -2 -1 -9 -1 

EDIT1:

有索引或列重複值。

print (df.columns.is_unique) 
True 
print (df.index.is_unique) 
False 

所以需要唯一索引添加reset_index

df = df.reset_index(drop=True) 
df['new '] = df.lookup(df.index, df['ref'].astype(str)) 
print (df) 
    ref 1 2 3 4 5 new 
0 1 -3 -2 -9 0 -2 -3 
1 3 -1 -2 -5 3 -5 -5 
2 5 -4 -7 -4 2 -1 -1 
3 4 -2 -4 -2 -1 -9 -1 
4 1 -2 -3 -1 -3 -3 -2 
+0

你好,感謝您的諮詢!但是我收到了錯誤消息msg pandas.core.indexes.base.InvalidIndexError:Reindexing只對唯一賦值的索引對象有效。在ref列中,有相同的值,我認爲這是由這個錯誤引起的。 – user8159259

+0

它是如何工作的? – jezrael

+0

我改變了我的數據框從以前的帖子 – user8159259