當前位置: 首頁>>代碼示例>>Python>>正文


Python pandas.pivot方法代碼示例

本文整理匯總了Python中pandas.pivot方法的典型用法代碼示例。如果您正苦於以下問題:Python pandas.pivot方法的具體用法?Python pandas.pivot怎麽用?Python pandas.pivot使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pandas的用法示例。


在下文中一共展示了pandas.pivot方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_pivot_with_list_like_values

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import pivot [as 別名]
def test_pivot_with_list_like_values(self, values, method):
        # issue #17160
        df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two', 'two'],
                           'bar': ['A', 'B', 'C', 'A', 'B', 'C'],
                           'baz': [1, 2, 3, 4, 5, 6],
                           'zoo': ['x', 'y', 'z', 'q', 'w', 't']})

        if method:
            result = df.pivot(index='foo', columns='bar', values=values)
        else:
            result = pd.pivot(df, index='foo', columns='bar', values=values)

        data = [[1, 2, 3, 'x', 'y', 'z'],
                [4, 5, 6, 'q', 'w', 't']]
        index = Index(data=['one', 'two'], name='foo')
        columns = MultiIndex(levels=[['baz', 'zoo'], ['A', 'B', 'C']],
                             codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]],
                             names=[None, 'bar'])
        expected = DataFrame(data=data, index=index,
                             columns=columns, dtype='object')
        tm.assert_frame_equal(result, expected) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:23,代碼來源:test_pivot.py

示例2: test_pivot_with_list_like_values_nans

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import pivot [as 別名]
def test_pivot_with_list_like_values_nans(self, values, method):
        # issue #17160
        df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two', 'two'],
                           'bar': ['A', 'B', 'C', 'A', 'B', 'C'],
                           'baz': [1, 2, 3, 4, 5, 6],
                           'zoo': ['x', 'y', 'z', 'q', 'w', 't']})

        if method:
            result = df.pivot(index='zoo', columns='foo', values=values)
        else:
            result = pd.pivot(df, index='zoo', columns='foo', values=values)

        data = [[np.nan, 'A', np.nan, 4],
                [np.nan, 'C', np.nan, 6],
                [np.nan, 'B', np.nan, 5],
                ['A', np.nan, 1, np.nan],
                ['B', np.nan, 2, np.nan],
                ['C', np.nan, 3, np.nan]]
        index = Index(data=['q', 't', 'w', 'x', 'y', 'z'], name='zoo')
        columns = MultiIndex(levels=[['bar', 'baz'], ['one', 'two']],
                             codes=[[0, 0, 1, 1], [0, 1, 0, 1]],
                             names=[None, 'foo'])
        expected = DataFrame(data=data, index=index,
                             columns=columns, dtype='object')
        tm.assert_frame_equal(result, expected) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:27,代碼來源:test_pivot.py

示例3: test_pivot_index_with_nan

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import pivot [as 別名]
def test_pivot_index_with_nan(self, method):
        # GH 3588
        nan = np.nan
        df = DataFrame({'a': ['R1', 'R2', nan, 'R4'],
                        'b': ['C1', 'C2', 'C3', 'C4'],
                        'c': [10, 15, 17, 20]})
        if method:
            result = df.pivot('a', 'b', 'c')
        else:
            result = pd.pivot(df, 'a', 'b', 'c')
        expected = DataFrame([[nan, nan, 17, nan], [10, nan, nan, nan],
                              [nan, 15, nan, nan], [nan, nan, nan, 20]],
                             index=Index([nan, 'R1', 'R2', 'R4'], name='a'),
                             columns=Index(['C1', 'C2', 'C3', 'C4'], name='b'))
        tm.assert_frame_equal(result, expected)
        tm.assert_frame_equal(df.pivot('b', 'a', 'c'), expected.T)

        # GH9491
        df = DataFrame({'a': pd.date_range('2014-02-01', periods=6, freq='D'),
                        'c': 100 + np.arange(6)})
        df['b'] = df['a'] - pd.Timestamp('2014-02-02')
        df.loc[1, 'a'] = df.loc[3, 'a'] = nan
        df.loc[1, 'b'] = df.loc[4, 'b'] = nan

        if method:
            pv = df.pivot('a', 'b', 'c')
        else:
            pv = pd.pivot(df, 'a', 'b', 'c')
        assert pv.notna().values.sum() == len(df)

        for _, row in df.iterrows():
            assert pv.loc[row['a'], row['b']] == row['c']

        if method:
            result = df.pivot('b', 'a', 'c')
        else:
            result = pd.pivot(df, 'b', 'a', 'c')
        tm.assert_frame_equal(result, pv.T) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:40,代碼來源:test_pivot.py

示例4: test_pivot_periods

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import pivot [as 別名]
def test_pivot_periods(self, method):
        df = DataFrame({'p1': [pd.Period('2013-01-01', 'D'),
                               pd.Period('2013-01-02', 'D'),
                               pd.Period('2013-01-01', 'D'),
                               pd.Period('2013-01-02', 'D')],
                        'p2': [pd.Period('2013-01', 'M'),
                               pd.Period('2013-01', 'M'),
                               pd.Period('2013-02', 'M'),
                               pd.Period('2013-02', 'M')],
                        'data1': np.arange(4, dtype='int64'),
                        'data2': np.arange(4, dtype='int64')})

        exp_col1 = Index(['data1', 'data1', 'data2', 'data2'])
        exp_col2 = pd.PeriodIndex(['2013-01', '2013-02'] * 2,
                                  name='p2', freq='M')
        exp_col = pd.MultiIndex.from_arrays([exp_col1, exp_col2])
        expected = DataFrame([[0, 2, 0, 2], [1, 3, 1, 3]],
                             index=pd.PeriodIndex(['2013-01-01', '2013-01-02'],
                                                  name='p1', freq='D'),
                             columns=exp_col)
        if method:
            pv = df.pivot(index='p1', columns='p2')
        else:
            pv = pd.pivot(df, index='p1', columns='p2')
        tm.assert_frame_equal(pv, expected)

        expected = DataFrame([[0, 2], [1, 3]],
                             index=pd.PeriodIndex(['2013-01-01', '2013-01-02'],
                                                  name='p1', freq='D'),
                             columns=pd.PeriodIndex(['2013-01', '2013-02'],
                                                    name='p2', freq='M'))
        if method:
            pv = df.pivot(index='p1', columns='p2', values='data1')
        else:
            pv = pd.pivot(df, index='p1', columns='p2', values='data1')
        tm.assert_frame_equal(pv, expected) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:38,代碼來源:test_pivot.py

示例5: test_pivot_with_tuple_of_values

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import pivot [as 別名]
def test_pivot_with_tuple_of_values(self, method):
        # issue #17160
        df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two', 'two'],
                           'bar': ['A', 'B', 'C', 'A', 'B', 'C'],
                           'baz': [1, 2, 3, 4, 5, 6],
                           'zoo': ['x', 'y', 'z', 'q', 'w', 't']})
        with pytest.raises(KeyError, match=r"^\('bar', 'baz'\)$"):
            # tuple is seen as a single column name
            if method:
                df.pivot(index='zoo', columns='foo', values=('bar', 'baz'))
            else:
                pd.pivot(df, index='zoo', columns='foo', values=('bar', 'baz')) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:14,代碼來源:test_pivot.py

示例6: test_margins_no_values_no_cols

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import pivot [as 別名]
def test_margins_no_values_no_cols(self):
        # Regression test on pivot table: no values or cols passed.
        result = self.data[['A', 'B']].pivot_table(
            index=['A', 'B'], aggfunc=len, margins=True)
        result_list = result.tolist()
        assert sum(result_list[:-1]) == result_list[-1] 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:8,代碼來源:test_pivot.py

示例7: test_margins_no_values_two_rows

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import pivot [as 別名]
def test_margins_no_values_two_rows(self):
        # Regression test on pivot table: no values passed but rows are a
        # multi-index
        result = self.data[['A', 'B', 'C']].pivot_table(
            index=['A', 'B'], columns='C', aggfunc=len, margins=True)
        assert result.All.tolist() == [3.0, 1.0, 4.0, 3.0, 11.0] 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:8,代碼來源:test_pivot.py

示例8: test_margins_no_values_one_row_one_col

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import pivot [as 別名]
def test_margins_no_values_one_row_one_col(self):
        # Regression test on pivot table: no values passed but row and col
        # defined
        result = self.data[['A', 'B']].pivot_table(
            index='A', columns='B', aggfunc=len, margins=True)
        assert result.All.tolist() == [4.0, 7.0, 11.0] 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:8,代碼來源:test_pivot.py

示例9: test_margins_no_values_two_row_two_cols

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import pivot [as 別名]
def test_margins_no_values_two_row_two_cols(self):
        # Regression test on pivot table: no values passed but rows and cols
        # are multi-indexed
        self.data['D'] = ['a', 'b', 'c', 'd',
                          'e', 'f', 'g', 'h', 'i', 'j', 'k']
        result = self.data[['A', 'B', 'C', 'D']].pivot_table(
            index=['A', 'B'], columns=['C', 'D'], aggfunc=len, margins=True)
        assert result.All.tolist() == [3.0, 1.0, 4.0, 3.0, 11.0] 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:10,代碼來源:test_pivot.py

示例10: test_pivot_with_tz

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import pivot [as 別名]
def test_pivot_with_tz(self, method):
        # GH 5878
        df = DataFrame({'dt1': [datetime(2013, 1, 1, 9, 0),
                                datetime(2013, 1, 2, 9, 0),
                                datetime(2013, 1, 1, 9, 0),
                                datetime(2013, 1, 2, 9, 0)],
                        'dt2': [datetime(2014, 1, 1, 9, 0),
                                datetime(2014, 1, 1, 9, 0),
                                datetime(2014, 1, 2, 9, 0),
                                datetime(2014, 1, 2, 9, 0)],
                        'data1': np.arange(4, dtype='int64'),
                        'data2': np.arange(4, dtype='int64')})

        df['dt1'] = df['dt1'].apply(lambda d: pd.Timestamp(d, tz='US/Pacific'))
        df['dt2'] = df['dt2'].apply(lambda d: pd.Timestamp(d, tz='Asia/Tokyo'))

        exp_col1 = Index(['data1', 'data1', 'data2', 'data2'])
        exp_col2 = pd.DatetimeIndex(['2014/01/01 09:00',
                                     '2014/01/02 09:00'] * 2,
                                    name='dt2', tz='Asia/Tokyo')
        exp_col = pd.MultiIndex.from_arrays([exp_col1, exp_col2])
        expected = DataFrame([[0, 2, 0, 2], [1, 3, 1, 3]],
                             index=pd.DatetimeIndex(['2013/01/01 09:00',
                                                     '2013/01/02 09:00'],
                                                    name='dt1',
                                                    tz='US/Pacific'),
                             columns=exp_col)

        if method:
            pv = df.pivot(index='dt1', columns='dt2')
        else:
            pv = pd.pivot(df, index='dt1', columns='dt2')
        tm.assert_frame_equal(pv, expected)

        expected = DataFrame([[0, 2], [1, 3]],
                             index=pd.DatetimeIndex(['2013/01/01 09:00',
                                                     '2013/01/02 09:00'],
                                                    name='dt1',
                                                    tz='US/Pacific'),
                             columns=pd.DatetimeIndex(['2014/01/01 09:00',
                                                       '2014/01/02 09:00'],
                                                      name='dt2',
                                                      tz='Asia/Tokyo'))

        if method:
            pv = df.pivot(index='dt1', columns='dt2', values='data1')
        else:
            pv = pd.pivot(df, index='dt1', columns='dt2', values='data1')
        tm.assert_frame_equal(pv, expected) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:51,代碼來源:test_pivot.py


注:本文中的pandas.pivot方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。