2017-04-13 7 views
2

これで、事前に作成されたデータフレームがあり、リストを追加しようとしています。簡略版では、以下の問題があります。Pandas - 既存のデータフレームへのリストの追加(列と同じ順序)

df = pd.DataFrame({'One': [], 
       'Another' : [], 
       'Third' : [], 
       'Last' : []}) 

は、それから私は、リストにいくつかのものを実行します。私はデータフレームでそれらをしたいと

new_obj = [] 
new_obj.append('1') 
new_obj.append('2') 
#I have to do the extend operation here 
new_obj.extend(['3','4']) 

は今、私はちょうど私のデータフレームの中に私のnew_objリストを追加したい、オブジェクトは同じ順序です。

だから、僕はやる:

df.loc[len(df.index)] = new_obj 

、結果として私が持っている:

Another Last One Third 
0  1 2 3  4 

なぜか。なぜそれが列の順序をaphabeticものに変更するのか。追加するときにどうすれば保存できますか?

答えて

2

注:列の順序を気にした場合...、代わりにこのようなあなたのDFを初期化自然。 DataFrameあなたが書くことができる(またはユーザーcollections.OrderedDict)のための正しい順序を指定するには:

df = pd.DataFrame({'One': [], 
        'Another' : [], 
        'Third' : [], 
        'Last' : []}, columns=["One", "Another", "Third", "Last"]) 

一方、あなたが本当にDataFrameで順番を気にしないならば、あなただけ明示的に定義することができますカラムは、彼はあなたのアールは、単に代わりにdictを使用して追加することlist int型:他の人の答えが述べた

new_obj = {"One" : 1, "Anohter" : 2, "Third" : 3, "Last" : 4} 
df.loc[len(df.index)] = new_obj 
2

あなたの行df.loc[len(df.index)] = new_objは、列の順序を変更しませんでした。

ディクショナリキーの順序が不揃いなので、データフレームを作成するために辞書をpd.DataFrame()に渡すと、カラムの順序は必ずしも書かれているとは限りません。

確認するために、これを試してみてください:

df = pd.DataFrame({'One': [], 
       'Another' : [], 
       'Third' : [], 
       'Last' : []}) 

df.columns 

指数([ '別の'、 '最後'、 'ワン'、 '三']、DTYPE = 'オブジェクト')

Pythonでdictがによって順序付けられていないことを

columns = ['one', 'another', 'third', 'last'] 
df = pd.DataFrame(columns=columns) 
1

として、dictonaryキーが注文されていません。パラメータを使用append

One Another Third Last 
0 1  2  3 4 
1

import pandas as pd 
import collections 

mydict = collections.OrderedDict((('One', []), 
       ('Another', []), 
       ('Third', []), 
       ('Last', []))) 

df = pd.DataFrame.from_dict(mydict) 

new_obj = [] 
new_obj.append('1') 
new_obj.append('2') 
#I have to do the extend operation here 
new_obj.extend(['3','4']) 
df.loc[len(df.index)] = new_obj 
print df 

結果の下に示すように、あなたはdictの使用orderddictを注文したい場合はignore_index=True

df = pd.DataFrame(columns='One Another Third Last'.split()) 

new_obj = [] 
new_obj.append('1') 
new_obj.append('2') 
#I have to do the extend operation here 
new_obj.extend(['3','4']) 

# notice I created a `pd.Series` with `df.columns` as the index 
df.append(pd.Series(new_obj, df.columns), ignore_index=True) 

    One Another Third Last 
0 1  2  3 4 
関連する問題