Ustawianie kolejności kolumn w ramce danych pandy

Czy istnieje sposób, aby zmienić kolejność kolumn w ramce danych pandy w oparciu o moje osobiste preferencje (tzn. nie posortowane alfabetycznie lub numerycznie, ale bardziej zgodnie z pewnymi konwencjami)?

Prosty przykład:

frame = pd.DataFrame({
        'one thing':[1,2,3,4],
        'second thing':[0.1,0.2,1,2],
        'other thing':['a','e','i','o']})

Produkuje to:

   one thing other thing  second thing
0          1           a           0.1
1          2           e           0.2
2          3           i           1.0
3          4           o           2.0

Ale zamiast tego, chciałbym to:

   one thing second thing  other thing
0          1           0.1           a
1          2           0.2           e
2          3           1.0           i
3          4           2.0           o

(proszę podać ogólne rozwiązanie, a nie specyficzne dla tego przypadku. Wielkie dzięki.)

 121
Author: piRSquared, 2017-01-31

9 answers

Po prostu wybierz zamówienie samodzielnie, wpisując nazwy kolumn. Uwaga na podwójne nawiasy:

frame = frame[['column I want first', 'column I want second'...etc.]]
 179
Author: A.Kot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-31 22:36:06

Możesz użyć tego:

columnsTitles = ['onething', 'secondthing', 'otherthing']

frame = frame.reindex(columns=columnsTitles)
 96
Author: Okroshiashvili,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-11-13 17:39:02

Oto rozwiązanie, z którego korzystam bardzo często. Gdy masz duży zestaw danych z mnóstwem kolumn, zdecydowanie nie chcesz ręcznie zmieniać wszystkich kolumn.

To, co możesz i najprawdopodobniej chcesz zrobić, to po prostu zamówić kilka pierwszych kolumn, których często używasz, i pozwolić, aby wszystkie inne kolumny były po prostu sobą. Jest to wspólne podejście w R. df %>%select(one, two, three, everything())

Więc możesz najpierw ręcznie wpisać kolumny, które chcesz zamówić i być umieszczone przed wszystkimi innymi kolumnami w Lista cols_to_order.

Następnie tworzysz listę dla nowych kolumn, łącząc resztę kolumn:

new_columns = cols_to_order + (frame.columns.drop(cols_to_order).tolist())

Następnie możesz użyć new_columns zgodnie z innymi rozwiązaniami.

import pandas as pd
frame = pd.DataFrame({
    'one thing': [1, 2, 3, 4],
    'other thing': ['a', 'e', 'i', 'o'],
    'more things': ['a', 'e', 'i', 'o'],
    'second thing': [0.1, 0.2, 1, 2],
})

cols_to_order = ['one thing', 'second thing']
new_columns = cols_to_order + (frame.columns.drop(cols_to_order).tolist())
frame = frame[new_columns]

   one thing  second thing other thing more things
0          1           0.1           a           a
1          2           0.2           e           e
2          3           1.0           i           i
3          4           2.0           o           o
 55
Author: Lala La,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-06 05:01:02

Można też zrobić coś takiego df = df[['x', 'y', 'a', 'b']]

import pandas as pd
frame = pd.DataFrame({'one thing':[1,2,3,4],'second thing':[0.1,0.2,1,2],'other thing':['a','e','i','o']})
frame = frame[['second thing', 'other thing', 'one thing']]
print frame
   second thing other thing  one thing
0           0.1           a          1
1           0.2           e          2
2           1.0           i          3
3           2.0           o          4

Możesz również uzyskać listę kolumn za pomocą:

cols = list(df.columns.values)

Wyjście wytworzy coś takiego:

['x', 'y', 'a', 'b']

, który następnie można łatwo zmienić ręcznie.

 28
Author: omri_saadon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-31 22:40:32

Zbuduj go z listą zamiast słownika

frame = pd.DataFrame([
        [1, .1, 'a'],
        [2, .2, 'e'],
        [3,  1, 'i'],
        [4,  4, 'o']
    ], columns=['one thing', 'second thing', 'other thing'])

frame

   one thing  second thing other thing
0          1           0.1           a
1          2           0.2           e
2          3           1.0           i
3          4           4.0           o
 13
Author: piRSquared,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-31 22:56:09

Możesz również użyć OrderedDict:

In [183]: from collections import OrderedDict

In [184]: data = OrderedDict()

In [185]: data['one thing'] = [1,2,3,4]

In [186]: data['second thing'] = [0.1,0.2,1,2]

In [187]: data['other thing'] = ['a','e','i','o']

In [188]: frame = pd.DataFrame(data)

In [189]: frame
Out[189]:
   one thing  second thing other thing
0          1           0.1           a
1          2           0.2           e
2          3           1.0           i
3          4           2.0           o
 10
Author: MaxU,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-31 22:40:54

Dodaj parametr 'columns':

frame = pd.DataFrame({
        'one thing':[1,2,3,4],
        'second thing':[0.1,0.2,1,2],
        'other thing':['a','e','i','o']},
        columns=['one thing', 'second thing', 'other thing']
)
 6
Author: irene,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-30 07:45:05

Spróbuj indeksować (więc chcesz ogólnego rozwiązania nie tylko dla tego, więc kolejność indeksów może być taka, jak chcesz):

l=[0,2,1] # index order
frame=frame[[frame.columns[i] for i in l]]

Teraz:

print(frame)

Jest:

   one thing second thing  other thing
0          1           0.1           a
1          2           0.2           e
2          3           1.0           i
3          4           2.0           o
 6
Author: U11-Forward,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-17 07:04:09

Uważam to za najbardziej proste i działające:

df = pd.DataFrame({
        'one thing':[1,2,3,4],
        'second thing':[0.1,0.2,1,2],
        'other thing':['a','e','i','o']})

df = df[['one thing','second thing', 'other thing']]
 -2
Author: Sando K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-02-19 12:31:30