2017-05-08 65 views
0

我能夠生成一個具有相同列名的熊貓數據框。 熊貓數據框是否正常? 我該如何選擇兩列之一? 使用相同的名稱,它的結果是產生數據框的兩個列作爲輸出?具有相同列名稱的熊貓數據框 - 它是否有效的過程?

舉例如下:

# Producing a new empty pd dataset 
dataset=pd.DataFrame() 

# fill in a list with values to be added to the dataset later 
cases=[1]*10 

# Adding the list of values in the dataset, and naming the variable/column 
dataset["id"]=cases 

# making a list of columns as it is displayed below: 
data_columns = ["id", "id"] 

# Then, we call the pd dataframe using the defined column names: 
dataset_new=dataset[data_columns] 

# dataset_new 
# It has as a result two columns with identical names. 
# How can I process only one of the two dataset columns? 

    id id 
0 1 1 
1 1 1 
2 1 1 
3 1 1 
4 1 1 
5 1 1 
6 1 1 
7 1 1 

回答

2

可以使用.iloc訪問任一列。

dataset_new.iloc[:,0] 

dataset_new.iloc[:,1] 

,當然,當您將它們都設定爲 'ID' 使用你可以爲你列就像你一樣:

dataset_new.column = ['id_1', 'id_2'] 
+0

但我猜我無法單獨通過名稱訪問它們? –

+0

不,這個名字是一個標籤,兩列都有相同的標籤。您可以通過那裏獲得索引值。 –

1
df = pd.DataFrame() 
lst = ['1', '2', '3'] 
df[0] = lst 
df[1] = lst 
df.rename(columns={0:'id'}, inplace=True) 
df.rename(columns={1:'id'}, inplace=True) 
print(df[[1]]) 
相關問題