2017-11-08 2 views
1

Ich habe einen Datenrahmen, der wie folgt aussieht:Pandas lang Wide-Format mit Multi-Index

data.head() 
Out[2]: 
     Area Area Id     Variable Name Variable Id Year \ 
0 Argentina  9 Conservation agriculture area  4454 1982 
1 Argentina  9 Conservation agriculture area  4454 1987 
2 Argentina  9 Conservation agriculture area  4454 1992 
3 Argentina  9 Conservation agriculture area  4454 1997 
4 Argentina  9 Conservation agriculture area  4454 2002 
    Value Symbol Md 
0  2.0    
1  6.0    
2 500.0  

, Ich mag würde so verschwenken, dass Variable Name die Spalten sind, Area und Year sind der Index und Value sind die Werte. Die intuitive Art und Weise zu mir mit:

data.pivot(index=['Area', 'Year'], columns='Variable Name', values='Value) 

Allerdings erhalte ich die Fehlermeldung:

Traceback (most recent call last): 
    File "C:\Users\patri\Miniconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code 
    exec(code_obj, self.user_global_ns, self.user_ns) 
    File "<ipython-input-4-4c786386b703>", line 1, in <module> 
    pd.concat(data_list).pivot(index=['Area', 'Year'], columns='Variable Name', values='Value') 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\frame.py", line 3853, in pivot 
    return pivot(self, index=index, columns=columns, values=values) 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 377, in pivot 
    index=MultiIndex.from_arrays([index, self[columns]])) 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\series.py", line 250, in __init__ 
    data = SingleBlockManager(data, index, fastpath=True) 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\internals.py", line 4117, in __init__ 
    fastpath=True) 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\internals.py", line 2719, in make_block 
    return klass(values, ndim=ndim, fastpath=fastpath, placement=placement) 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\internals.py", line 1844, in __init__ 
    placement=placement, **kwargs) 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\internals.py", line 115, in __init__ 
    len(self.mgr_locs))) 
ValueError: Wrong number of items passed 119611, placement implies 2 

Wie soll ich das verstehen? Ich habe auch einen anderen Weg versucht:

data.set_index(['Area', 'Variable Name', 'Year']).loc[:, 'Value'].unstack('Variable Name') 

zu versuchen, um das gleiche Ergebnis zu erhalten, aber ich bekomme diese Fehlermeldung:

Traceback (most recent call last): 
    File "C:\Users\patri\Miniconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code 
    exec(code_obj, self.user_global_ns, self.user_ns) 
    File "<ipython-input-5-222325ea01e1>", line 1, in <module> 
    pd.concat(data_list).set_index(['Area', 'Variable Name', 'Year']).loc[:, 'Value'].unstack('Variable Name') 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\series.py", line 2028, in unstack 
    return unstack(self, level, fill_value) 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 458, in unstack 
    fill_value=fill_value) 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 110, in __init__ 
    self._make_selectors() 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 148, in _make_selectors 
    raise ValueError('Index contains duplicate entries, ' 
ValueError: Index contains duplicate entries, cannot reshape 

Gibt es etwas falsch mit den Daten? Ich habe bestätigt, dass es keine doppelten Kombinationen von Area, Variable Name und Year in einer beliebigen Zeile des Datenrahmens gibt, also glaube ich nicht, dass es doppelte Einträge geben sollte, aber ich könnte falsch liegen. Wie kann ich vom Long- in das Wide-Format konvertieren, wenn diese beiden Methoden derzeit nicht funktionieren? Ich habe Antworten here und here überprüft, aber sie sind beide Fälle, in denen irgendeine Art I Ansammlung beteiligt ist.

Ich habe versucht, mit pivot_table wie so:

data.pivot_table(index=['Area', 'Year'], columns='Variable Name', values='Value') 

aber ich denke, irgendeine Art von Aggregation getan wird, und es gibt eine Menge von fehlenden Werten im Datensatz, die zu diesem Fehler führt:

Traceback (most recent call last): 
    File "C:\Users\patri\Miniconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code 
    exec(code_obj, self.user_global_ns, self.user_ns) 
    File "<ipython-input-7-77b28d2f0dbb>", line 1, in <module> 
    pd.concat(data_list).pivot_table(index=['Area', 'Year'], columns='Variable Name', values='Value') 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\reshape\pivot.py", line 136, in pivot_table 
    agged = grouped.agg(aggfunc) 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\groupby.py", line 4036, in aggregate 
    return super(DataFrameGroupBy, self).aggregate(arg, *args, **kwargs) 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\groupby.py", line 3468, in aggregate 
    result, how = self._aggregate(arg, _level=_level, *args, **kwargs) 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\base.py", line 435, in _aggregate 
    **kwargs), None 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\base.py", line 391, in _try_aggregate_string_function 
    return f(*args, **kwargs) 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\groupby.py", line 1037, in mean 
    return self._cython_agg_general('mean', **kwargs) 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\groupby.py", line 3354, in _cython_agg_general 
    how, alt=alt, numeric_only=numeric_only) 
    File "C:\Users\patri\Miniconda3\lib\site-packages\pandas\core\groupby.py", line 3425, in _cython_agg_blocks 
    raise DataError('No numeric types to aggregate') 
pandas.core.base.DataError: No numeric types to aggregate 
+0

Was ist 'data.pivot_table (Index = [ 'Area', 'Jahr'], Spalten = 'Variablenname', Werte = 'Value) '? – jezrael

+0

Ich habe vergessen zu erwähnen, dass ich auch diese Methode ausprobiert habe und einen weiteren Fehler bekommen habe. Ich denke, es hat damit zu tun, dass irgendeine Art von Aggregation mit fehlenden Werten im Datensatz durchgeführt wird. Bearbeitungsfrage – pbreach

+1

Bearbeitete Antwort. Es gibt ein Problem, dass Ihre Daten nicht numerisch sind. – jezrael

Antwort

1

ich glaube, Sie müssen erste Spalte Value in numerischen konvertieren und dann mit Standard-Aggregatfunktion verwendet pivot_tablemean:

#if all float data saved as strings 
data['Value'] = data['Value'].astype(float) 
#if some bad data like strings and first method return value error 
data['Value'] = pd.to_numeric(data['Value'], errors='coerce') 

data.pivot_table(index=['Area', 'Year'], columns='Variable Name', values='Value') 

Oder:

data.groupby(['Area', 'Variable Name', 'Year'])[ 'Value'].mean().unstack('Variable Name') 
+0

Ahhh, jetzt macht das Sinn! Ich habe versucht, in Float zu konvertieren, und ich bekam 'ValueError: konnte die Zeichenfolge nicht in Float konvertieren '. Sieht so aus, als würde ich eine Minute brauchen, um die Daten ein wenig zu säubern und zurück zu kommen. – pbreach

+1

Ich füge eine andere Lösung hinzu. – jezrael