Jak wziąć kolumnę-plastry dataframe w pandy
Ładuję dane uczenia maszynowego z pliku csv. Pierwsze 2 kolumny to obserwacje, a pozostałe kolumny to cechy.
Obecnie wykonuję:
data = pandas.read_csv('mydata.csv')
Co daje coś w rodzaju:
data = pandas.DataFrame(np.random.rand(10,5), columns = list('abcde'))
Chciałbym podzielić tę ramkę na dwa ramki: jeden zawierający Kolumny a
i b
i jeden zawierający kolumny c
, d
i e
.
Nie da się napisać czegoś takiego
observations = data[:'c']
features = data['c':]
I ' m not sure what najlepsza metoda jest. Czy potrzebuję pd.Panel
?
Przy okazji, uważam indeksowanie ramek danych za dość niespójne: data['a']
jest dozwolone, ale data[0]
nie jest. Z drugiej strony, data['a':]
nie jest dozwolone, ale data[0:]
jest.
Czy jest ku temu jakiś praktyczny powód? Jest to naprawdę mylące, jeśli kolumny są indeksowane przez Int, biorąc pod uwagę, że data[0] != data[0:1]
9 answers
2017 odpowiedź-pandy 0.20: .ix jest przestarzały. Użyj .loc
Zobacz w dokumentacji
.loc
używa indeksowania opartego na etykietach do zaznaczania wierszy i kolumn. Etykiety są wartościami indeksu lub kolumn. Krojenie za pomocą .loc
zawiera ostatni element.
Załóżmy, że mamy ramkę danych z następującymi kolumnami:
foo
,bar
,quz
,ant
,cat
,sat
,dat
.
# selects all rows and all columns beginning at 'foo' up to and including 'sat'
df.loc[:, 'foo':'sat']
# foo bar quz ant cat sat
.loc
akceptuje ten sam kawałek notacja, którą listy Pythona wykonują zarówno dla wierszy, jak i kolumn. Slice notation being start:stop:step
# slice from 'foo' to 'cat' by every 2nd column
df.loc[:, 'foo':'cat':2]
# foo quz cat
# slice from the beginning to 'bar'
df.loc[:, :'bar']
# foo bar
# slice from 'quz' to the end by 3
df.loc[:, 'quz'::3]
# quz sat
# attempt from 'sat' to 'bar'
df.loc[:, 'sat':'bar']
# no columns returned
# slice from 'sat' to 'bar'
df.loc[:, 'sat':'bar':-1]
sat cat ant quz bar
# slice notation is syntatic sugar for the slice function
# slice from 'quz' to the end by 2 with slice function
df.loc[:, slice('quz',None, 2)]
# quz cat dat
# select specific columns with a list
# select columns foo, bar and dat
df.loc[:, ['foo','bar','dat']]
# foo bar dat
Możesz przecinać wiersze i kolumny. Na przykład, jeśli masz 5 wierszy z etykietami v
, w
, x
, y
, z
# slice from 'w' to 'y' and 'foo' to 'ant' by 3
df.loc['w':'y', 'foo':'ant':3]
# foo ant
# w
# x
# y
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-11-30 05:44:53
Ramka Danych.indeks ix jest tym, do czego chcesz mieć dostęp. To trochę mylące (zgadzam się, że indeksowanie pand jest czasami kłopotliwe!), ale następujące wydaje się robić to, co chcesz:
>>> df = DataFrame(np.random.rand(4,5), columns = list('abcde'))
>>> df.ix[:,'b':]
b c d e
0 0.418762 0.042369 0.869203 0.972314
1 0.991058 0.510228 0.594784 0.534366
2 0.407472 0.259811 0.396664 0.894202
3 0.726168 0.139531 0.324932 0.906575
Gdzie .ix [row slice, column slice] jest tym, co jest interpretowane. Więcej o pandach tutaj: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-advanced
Uwaga: .ix
jest przestarzały od Pandas v0. 20. Zamiast tego należy użyć .loc
lub .iloc
, odpowiednio.
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-08-14 09:51:40
Pozwala użyć titanic dataset z pakietu seaborn jako przykład
# Load dataset (pip install seaborn)
>> import seaborn.apionly as sns
>> titanic = sns.load_dataset('titanic')
Używanie nazw kolumn
>> titanic.loc[:,['sex','age','fare']]
Używanie indeksów kolumn
>> titanic.iloc[:,[2,3,6]]
Używanie ix (starszych niż Pandy <.wersja>
>> titanic.ix[:,[‘sex’,’age’,’fare’]]
Lub
>> titanic.ix[:,[2,3,6]]
Przy użyciu metody reindex
>> titanic.reindex(columns=['sex','age','fare'])
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-15 13:37:20
Również, biorąc pod uwagę DataFrame
Dane
Jak w twoim przykładzie, jeśli chcesz wyodrębnić tylko kolumnę a i D (np. 1.i 4. kolumnę), iloc mothod z ramki danych pandy jest tym, czego potrzebujesz i może być używany bardzo efektywnie. Wszystko, co musisz wiedzieć, to indeks kolumn, które chcesz wyodrębnić. Na przykład:
>>> data.iloc[:,[0,3]]
Da ci
a d
0 0.883283 0.100975
1 0.614313 0.221731
2 0.438963 0.224361
3 0.466078 0.703347
4 0.955285 0.114033
5 0.268443 0.416996
6 0.613241 0.327548
7 0.370784 0.359159
8 0.692708 0.659410
9 0.806624 0.875476
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
2014-02-25 15:33:29
Możesz przecinać Kolumny DataFrame
, odwołując się do nazw każdej kolumny na liście, w następujący sposób:
data = pandas.DataFrame(np.random.rand(10,5), columns = list('abcde'))
data_ab = data[list('ab')]
data_cde = data[list('cde')]
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
2012-05-19 15:02:43
A jeśli przyszedłeś tutaj, szukając cięcia dwóch zakresów kolumn i łączenia ich ze sobą (tak jak ja), możesz zrobić coś w stylu
op = df[list(df.columns[0:899]) + list(df.columns[3593:])]
print op
Utworzy to nowy dataframe z pierwszymi 900 kolumnami i (wszystkie) kolumnami > 3593 (zakładając, że masz jakieś 4000 kolumn w zestawie danych).
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
2014-10-11 23:21:52
Oto jak możesz użyć różnych metod do selektywnego krojenia kolumn, w tym selektywnego krojenia kolumn na podstawie etykiet, indeksów i zakresów.
In [37]: import pandas as pd
In [38]: import numpy as np
In [43]: df = pd.DataFrame(np.random.rand(4,7), columns = list('abcdefg'))
In [44]: df
Out[44]:
a b c d e f g
0 0.409038 0.745497 0.890767 0.945890 0.014655 0.458070 0.786633
1 0.570642 0.181552 0.794599 0.036340 0.907011 0.655237 0.735268
2 0.568440 0.501638 0.186635 0.441445 0.703312 0.187447 0.604305
3 0.679125 0.642817 0.697628 0.391686 0.698381 0.936899 0.101806
In [45]: df.loc[:, ["a", "b", "c"]] ## label based selective column slicing
Out[45]:
a b c
0 0.409038 0.745497 0.890767
1 0.570642 0.181552 0.794599
2 0.568440 0.501638 0.186635
3 0.679125 0.642817 0.697628
In [46]: df.loc[:, "a":"c"] ## label based column ranges slicing
Out[46]:
a b c
0 0.409038 0.745497 0.890767
1 0.570642 0.181552 0.794599
2 0.568440 0.501638 0.186635
3 0.679125 0.642817 0.697628
In [47]: df.iloc[:, 0:3] ## index based column ranges slicing
Out[47]:
a b c
0 0.409038 0.745497 0.890767
1 0.570642 0.181552 0.794599
2 0.568440 0.501638 0.186635
3 0.679125 0.642817 0.697628
### with 2 different column ranges, index based slicing:
In [49]: df[df.columns[0:1].tolist() + df.columns[1:3].tolist()]
Out[49]:
a b c
0 0.409038 0.745497 0.890767
1 0.570642 0.181552 0.794599
2 0.568440 0.501638 0.186635
3 0.679125 0.642817 0.697628
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-06-19 21:56:49
Jego odpowiednik
>>> print(df2.loc[140:160,['Relevance','Title']])
>>> print(df2.ix[140:160,[3,7]])
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-07-05 09:28:25
Jeśli ramka Danych wygląda tak:
group name count
fruit apple 90
fruit banana 150
fruit orange 130
vegetable broccoli 80
vegetable kale 70
vegetable lettuce 125
I wyjście może być jak
group name count
0 fruit apple 90
1 fruit banana 150
2 fruit orange 130
Jeśli używasz operatora logicznego np.logical_not
df[np.logical_not(df['group'] == 'vegetable')]
Więcej o
Https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.logic.html
Inne operatory logiczne
Logical_and(x1, x2, / [, out, where,...]) Oblicz wartość prawdy elementy X1 i X2.
Logical_or (x1, x2, / [, out, where, casting, ...]) Oblicz wartość prawdy elementu X1 lub X2.
- logical_not(x, / [, out, where, casting, ...]) Oblicz prawdę wartość nie x element-wise.
- logical_xor(x1, x2, / [, out, where,..]) Oblicz wartość prawdy X1 XOR x2, pierwiastkowo.
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-08-08 16:54:02