Python Pandas –操作

熊猫支持非常有用的操作,如下所示,

考虑下面的dataFrame,

import numpy as np
import pandas as pd

df = pd.DataFrame({
  'col1': [1, 2, 3, 4],
  'col2': [444, 555, 666, 444],
  'col3': ['abc', 'def', 'ghi', 'xyz']
})

print(df.head())

'''
Output:
   col1  col2 col3
0     1   444  abc
1     2   555  def
2     3   666  ghi
3     4   444  xyz
'''

在数据框中查找唯一值

为了从列中找到唯一值,

# 返回所有唯一值的numpy数组
print(df['col2'].unique() )
# 输出:array([444,555,666])

# 返回长度/唯一值的数量 
# 在一个numpy数组中
print(df['col2'].nunique())
# 输出3

# 如果我们想要唯一值表
# 他们出现了多少次
print(df['col2'].value_counts() )
'''
Output:
444    2
555    1
666    1
Name: col2, dtype: int64
'''

从数据框中选择数据

看dataFrame,

使用条件选择,我们可以选择以下数据,

print(df['col1']>2)

'''
Output:
0    False
1    False
2     True
3     True
Name: col1, dtype: bool
'''

print(df[(df['col1']>2)])

'''
Output:
   col1  col2 col3
2     3   666  ghi
3     4   444  xyz
'''

print(df[df['col1']>2 & (df['col2']==44)])

'''
Output:
   col1  col2 col3
0     1   444  abc
1     2   555  def
2     3   666  ghi
3     4   444  xyz
'''

应用方法

考虑一个简单的方法,

def times2(x):
  return x*2

我们已经知道我们可以抓住一列并从中调用一个内置函数。如下

print(df['col1'].sum())
# 输出:10

现在,为了应用自定义功能(例如上面定义的时间(times2)),熊猫提供了执行此功能的选项,如下所述,

print(df['col2'].apply(times2))

'''
Output:
0     888
1    1110
2    1332
3     888
Name: col2, dtype: int64
'''

应用内置功能,

print(df['col3'].apply(len))

'''
Output:
0    3
1    3
2    3
3    3
Name: col3, dtype: int64
'''

当与lambda表达式结合使用时,apply方法将更强大。例如,

print(df['col2'].apply(lambda x: x*2))

'''
Output:
0     888
1    1110
2    1332
3     888
Name: col2, dtype: int64
'''

更多操作

# 返回列名
print(df.columns) 
# 输出:索引(['col1','col2','col3'],dtype ='object')

#由于这是一个rangeindex,因此它实际上会报告 
# 也可以开始,停止和步进值
print(df.index)
# 输出:RangeIndex(开始= 0,停止= 4,步骤= 1)

# 按栏排序
print(df.sort_values('col2'))

'''
Output:
   col1  col2 col3
0     1   444  abc
3     4   444  xyz
1     2   555  def
2     3   666  ghi
'''

在以上结果中,请注意索引值不会更改,这是为了确保保留这些值。

一片空白

# 一片空白
print(df.isnull())

'''
Output
    col1   col2   col3
0  False  False  False
1  False  False  False
2  False  False  False
3  False  False  False
'''

isnull()会返回布尔值的数据框指示值是否是空或不是。在上面的代码中,由于我们的数据帧中有空值,因此我们得到的布尔值均为false。

降低NAN值

print(df.dropna())

'''
Output:
   col1  col2 col3
0     1   444  abc
1     2   555  def
2     3   666  ghi
3     4   444  xyz
'''

用自定义值填充NAN值

df = pd.DataFrame({
  'col1': [1, 2, 3, np.nan],
  'col2': [np.nan, 555, 666, 444],
  'col3': ['abc', 'def', 'ghi', 'xyz']
})

print(df)

'''
Output:
   col1   col2 col3
0   1.0    NaN  abc
1   2.0  555.0  def
2   3.0  666.0  ghi
3   NaN  444.0  xyz
'''

print(df.fillna('FILL'))

'''
Output:
   col1  col2 col3
0     1  FILL  abc
1     2   555  def
2     3   666  ghi
3  FILL   444  xyz
'''

数据透视表的用法

Advanced Excel用户将熟悉此方法。考虑一个新的dataFrame,

data = {
  'A': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'],
  'B': ['one', 'one', 'two', 'two', 'one', 'one'],
  'C': ['x', 'y', 'x', 'y', 'x', 'y'],
  'D': [1, 3, 2, 5, 4, 1]
}

df = pd.DataFrame(data)

print(df)

'''
Output:
     A    B  C  D
0  foo  one  x  1
1  foo  one  y  3
2  foo  two  x  2
3  bar  two  y  5
4  bar  one  x  4
5  bar  one  y  1
'''

数据透视表创建一个多索引dataFrame。数据透视表采用三个主要参数,即值,索引和列。

print(df.pivot_table(values='D',index=['A', 'B'],columns=['C']))

'''
Output:
      C        x    y
A    B            
bar one  4.0  1.0
      two  NaN  5.0
foo one  1.0  3.0
      two  2.0  NaN
'''