Pandas共通操作整理(継続更新)

パンダ共通操作配置

1. データ定義

import pandas as pd
import numpy as np

#定义dataframe
# 数据是元组,索引是list 
df = pd.DataFrame({'no':[1,2,3,4,5],'score':[66,85,88,95,75]},
      index=['a','b','c','d','e'])

df.index.name='index'
print(df)

#通过元组定义dataframe
dic = {'key1':[1,2,3], 'key2':['a','b','c']}
df = pd.DataFrame(dic)
df.index.name='index'
#调用列值,一般用df['key1']
print(df.key1,df.key2)

結果:

       no  score
index           
a       1     66
b       2     85
c       3     88
d       4     95
e       5     75
index
0    1
1    2
2    3
Name: key1, dtype: int64 index
0    a
1    b
2    c
Name: key2, dtype: object

2.列を追加する

#通过元组定义dataframe
dic = {'key1':[1,2,3], 'key2':['a','b','c']}
df = pd.DataFrame(dic)
df.index.name='index'
#增加列
# 通过list增加,默认在列最后增加新列
lst=[88,99,77]
df['key3'] = lst

#按列的位置插入列,在第一列之后插入新列
df.insert(1,'new',lst)

# df的index 自动到df1中
df1 = df[['key1','key2']]
print(df)
print(df1)

結果は次のとおりです。

       key1  new key2  key3
index                      
0         1   88    a    88
1         2   99    b    99
2         3   77    c    77
       key1 key2
index           
0         1    a
1         2    b
2         3    c

3. 行を追加

#增加行
lst=[4,66,'d',66]
df.loc[len(df.index)] = lst
print(df)
#如果不加在最后一行,数据将会被替换
df.loc[1] = lst
print(df)

結果は次のようになります。
最初に行が追加されるときは、最後の行が追加され、インデックス番号は 3 になります。2
回目に行が追加されるときは、インデックス番号が 1 のレコードが実際に変更されます。


       key1  new key2  key3
index                      
0         1   88    a    88
1         2   99    b    99
2         3   77    c    77
3         4   66    d    66
       key1  new key2  key3
index                      
0         1   88    a    88
1         4   66    d    66
2         3   77    c    77
3         4   66    d    66

4. マージ

# Merge 功能 ,可以用于两个frame的查询合并

df1 = pd.DataFrame({'lkey': ['foo', 'bar', 'tar', 'baz', 'fool'],
                    'value': [1, 2, 3, 4, 5]})
df2 = pd.DataFrame({'rkey': ['foo', 'bar', 'baz', 'tool'],
                    'value': [5, 6, 7, 8]})
df1.index.name='index'
df2.index.name='index'

'''
how{‘left’, ‘right’, ‘outer’, ‘inner’, ‘cross’}, default ‘inner’
Type of merge to be performed.
left: use only keys from left frame, similar to a SQL left outer join; preserve key order.
right: use only keys from right frame, similar to a SQL right outer join; preserve key order.
outer: use union of keys from both frames, similar to a SQL full outer join; sort keys lexicographically.
inner: use intersection of keys from both frames, similar to a SQL inner join; preserve the order of the left keys.
cross: creates the cartesian product from both frames, preserves the order of the left keys.
'''

'''
on label or list
Column or index level names to join on. These must be found in both DataFrames. If on is None and not merging on indexes then this defaults to the intersection of the columns in both DataFrames.

left_on label or list, or array-like
Column or index level names to join on in the left DataFrame. Can also be an array or list of arrays of the length of the left DataFrame. These arrays are treated as if they are columns.

right_on label or list, or array-like
Column or index level names to join on in the right DataFrame. Can also be an array or list of arrays of the length of the right DataFrame. These arrays are treated as if they are columns.
'''

print('df1:')
print(df1)
print('df2:')
print(df2)

# df1 合并df2 ,按 值相等
df3=df1.merge(df2, on = 'value')
print('on value:')
print(df3)

# df1 合并 df2 按 左右连接相等
df3=df1.merge(df2, left_on='lkey', right_on='rkey')
print("left_on='lkey', right_on='rkey':")
print(df3)

# df1 合并 df2 按 左外连接
df3=df1.merge(df2, how='left',left_on='lkey', right_on='rkey')
print("how='left',left_on='lkey', right_on='rkey':")
print(df3)

# df1 合并 df2 按 右外连接
df3=df1.merge(df2, how='right',left_on='lkey', right_on='rkey')
print("how='right',left_on='lkey', right_on='rkey':")
print(df3)


結果は次のとおりです。

df1:
       lkey  value
index             
0       foo      1
1       bar      2
2       tar      3
3       baz      4
4      fool      5
df2:
       rkey  value
index             
0       foo      5
1       bar      6
2       baz      7
3      tool      8
on value:
   lkey  value rkey
0  fool      5  foo
left_on='lkey', right_on='rkey':
  lkey  value_x rkey  value_y
0  foo        1  foo        5
1  bar        2  bar        6
2  baz        4  baz        7
how='left',left_on='lkey', right_on='rkey':
   lkey  value_x rkey  value_y
0   foo        1  foo      5.0
1   bar        2  bar      6.0
2   tar        3  NaN      NaN
3   baz        4  baz      7.0
4  fool        5  NaN      NaN
how='right',left_on='lkey', right_on='rkey':
  lkey  value_x  rkey  value_y
0  foo      1.0   foo        5
1  bar      2.0   bar        6
2  baz      4.0   baz        7
3  NaN      NaN  tool        8

詳細については、英語の説明を参照してください。これは、SQL の内部結合と外部結合の概念に似ています。

5. 参加する

値による結合、インデックスによる結合。

# Join
# 新版本中没有concat和append 方法

df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'],
                   'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})
other = pd.DataFrame({'key': ['K0', 'K1', 'K2','K6'],
                      'B': ['B0', 'B1', 'B2','B6']})
print('df:')
print(df)

print('other:')
print(other)

# 列名增加后缀 ,原来列名保留
df1 = df.join(other, lsuffix='_caller', rsuffix='_other')
print('df1:')
print(df1)

#按key合并,但是以df为主,key相同,使用df的key 和 other的key 
df2=df.set_index('key').join(other.set_index('key'))
print('df2:')
print(df2)

# 对于key有重复的情况,按key合并,做笛卡尔积,df中K1有3个,other中K1有2个,join后,有6个key为K1的值
df = pd.DataFrame({'key': ['K0', 'K1', 'K1', 'K3', 'K0', 'K1'],
                   'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})

other = pd.DataFrame({'key': ['K0', 'K1', 'K2','K1'],
                      'B': ['B0', 'B1', 'B2','B6']})

df3=df.set_index('key').join(other.set_index('key'))
print('df3:')
print(df3)

結果は次のとおりです。

df:
  key   A
0  K0  A0
1  K1  A1
2  K2  A2
3  K3  A3
4  K4  A4
5  K5  A5
other:
  key   B
0  K0  B0
1  K1  B1
2  K2  B2
3  K6  B6
df1:
  key_caller   A key_other    B
0         K0  A0        K0   B0
1         K1  A1        K1   B1
2         K2  A2        K2   B2
3         K3  A3        K6   B6
4         K4  A4       NaN  NaN
5         K5  A5       NaN  NaN
df2:
      A    B
key         
K0   A0   B0
K1   A1   B1
K2   A2   B2
K3   A3  NaN
K4   A4  NaN
K5   A5  NaN
df3:
      A    B
key         
K0   A0   B0
K0   A4   B0
K1   A1   B1
K1   A1   B6
K1   A2   B1
K1   A2   B6
K1   A5   B1
K1   A5   B6
K3   A3  NaN

6. ドロップは行と列を削除します

ドロップのパラメータの説明を参照できます。

# 删除 列  行 
'''
Parameters
labelssingle label or list-like
Index or column labels to drop. A tuple will be used as a single label and not treated as a list-like.

axis{0 or ‘index’, 1 or ‘columns’}, default 0
Whether to drop labels from the index (0 or ‘index’) or columns (1 or ‘columns’).

indexsingle label or list-like
Alternative to specifying axis (labels, axis=0 is equivalent to index=labels).

columnssingle label or list-like
Alternative to specifying axis (labels, axis=1 is equivalent to columns=labels).

levelint or level name, optional
For MultiIndex, level from which the labels will be removed.

inplacebool, default False
If False, return a copy. Otherwise, do operation inplace and return None.

errors{‘ignore’, ‘raise’}, default ‘raise’
If ‘ignore’, suppress error and only existing labels are dropped.

DataFrame.drop(labels=None,axis=0, index=None, columns=None, inplace=False)

labels:要删除的行或列,用列表给出
axis:默认为0,指要删除的是行,删除列时需指定axis为1
index :直接指定要删除的行,删除多行可以使用列表作为参数
columns:直接指定要删除的列,删除多列可以使用列表作为参数
inplace: 默认为False,该删除操作不改变原数据;inplace = True时,改变原数据

'''

df = pd.DataFrame(np.arange(16).reshape(4, 4),
                  columns=['A', 'B', 'C', 'D'])

# 两种删除列的方式
# axis 
df1 = df.drop(['B', 'C'], axis=1)
print(df1)

# columns
df2 = df.drop(columns=['B', 'C'])
print(df2)


#在当前frame上删除列,保存
df.drop(['B', 'C'], axis=1, inplace = True)

# 删除行 ,按索引删除
df1 = df.drop([0, 1])
print(df1)

df.drop([0, 1], inplace = True)
print(df)

結果は次のとおりです。

 A   D
0   0   3
1   4   7
2   8  11
3  12  15
    A   D
0   0   3
1   4   7
2   8  11
3  12  15
    A   D
2   8  11
3  12  15
    A   D
2   8  11
3  12  15

7. 置換検索と置換

# 更新
df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
                   'B': [5, 6, 7, 8, 0],
                   'C': ['a', 'b', 'c', 'd', 'e']})
print('df:')
print(df)
# 按值替换
df1 = df.replace(0, 5)
print('df1:')
print(df1)

# 按list替换
df2 = df.replace([0, 1, 2, 3], 4)
print('df2:')
print(df2)

# 按list替换list
df3 = df.replace([0, 1, 2, 3], [4, 3, 2, 1])
print('df3:')
print(df3)

結果は次のとおりです。

df:
   A  B  C
0  0  5  a
1  1  6  b
2  2  7  c
3  3  8  d
4  4  0  e
df1:
   A  B  C
0  5  5  a
1  1  6  b
2  2  7  c
3  3  8  d
4  4  5  e
df2:
   A  B  C
0  4  5  a
1  4  6  b
2  4  7  c
3  4  8  d
4  4  4  e
df3:
   A  B  C
0  4  5  a
1  3  6  b
2  2  7  c
3  1  8  d
4  4  4  e

8. 課題

loc と iloc を使用して割り当てを見つけます。

# 赋值
df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
                   'B': [5, 6, 7, 8, 9],
                   'C': ['a', 'b', 'c', 'd', 'e']})
#print(df)

# 按行赋值
df.loc[2] = 9
print('按行赋值:')
print(df)

# 多行赋值
df.loc[2:3] = 10
print('多行赋值:')
print(df)

# 按列赋值
df['A'] =0
print('按列赋值:')
print(df)

# 多列赋值
df[['A','C']] =100
print('多列赋值:')
print(df)

# 元素赋值

df.loc[1,'A'] =1000
print('loc元素赋值:')
print(df)

df.iloc[1,2] = 2000
print('iloc元素赋值:')
print(df)

結果は次のとおりです。

按行赋值:
   A  B  C
0  0  5  a
1  1  6  b
2  9  9  9
3  3  8  d
4  4  9  e
多行赋值:
    A   B   C
0   0   5   a
1   1   6   b
2  10  10  10
3  10  10  10
4   4   9   e
按列赋值:
   A   B   C
0  0   5   a
1  0   6   b
2  0  10  10
3  0  10  10
4  0   9   e
多列赋值:
     A   B    C
0  100   5  100
1  100   6  100
2  100  10  100
3  100  10  100
4  100   9  100
loc元素赋值:
      A   B    C
0   100   5  100
1  1000   6  100
2   100  10  100
3   100  10  100
4   100   9  100
iloc元素赋值:
      A   B     C
0   100   5   100
1  1000   6  2000
2   100  10   100
3   100  10   100
4   100   9   100

9. locの使用法

loc は最も一般的に使用される位置決め方法です。

# loc

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
     index=['cobra', 'viper', 'sidewinder'],
     columns=['max_speed', 'shield'])
print(df)


#print(df.loc['viper'])

# index 返回多行
print('index 返回多行:')
print(df.loc[['viper', 'sidewinder']])

# 按 index column 定位元素
print('按 index column 定位元素:')
print(df.loc['cobra', 'shield'])

# 按 index column 定位多行,单列
print('按 index column 定位多行:')
print(df.loc['cobra':'viper', 'max_speed'])

print('按 index column 定位单列:')
print(df.loc[pd.Series([False, True, False],
       index=['viper', 'sidewinder', 'cobra'])])

# 按索引范围,增加一个索引

print('按索引范围,增加一个索引:')
print(df.loc[pd.Index(["cobra", "viper"], name="foo")])

# 按条件筛选
print('按条件筛选:')
print(df.loc[df['shield'] > 6])

# 行按条件筛选, 选择列
print('行按条件筛选, 选择列:')
print(df.loc[df['shield'] > 6, ['max_speed']])

結果は次のとおりです。

            max_speed  shield
cobra               1       2
viper               4       5
sidewinder          7       8
index 返回多行:
            max_speed  shield
viper               4       5
sidewinder          7       8
按 index column 定位元素:
2
按 index column 定位多行:
cobra    1
viper    4
Name: max_speed, dtype: int64
按 index column 定位单列:
            max_speed  shield
sidewinder          7       8
按索引范围,增加一个索引:
       max_speed  shield
foo                     
cobra          1       2
viper          4       5
按条件筛选:
            max_speed  shield
sidewinder          7       8
行按条件筛选, 选择列:
            max_speed
sidewinder          7

10. 位置条件

# loc 条件查询
df = pd.DataFrame(np.arange(20).reshape(5,4),
                  columns=['a','b','c','d'],
                  index=[1,2,3,4,5])
df.index.name = 'idx'
# 按行
print('按行:')
print (df[2:4])

# 按列
print('按列:')
print (df[['a','c']])

# 按列条件查询
print('按列条件查询:')
print(df.loc[df['a']>6])

print('按列条件查询,指定列:')
print(df.loc[df['a']>6,['a','d']])


# 按索引查询
print('按索引查询:')
print(df.loc[df.index>4])

print('按索引查询,指定列:')               
print(df.loc[df.index>4,['b','c','a']])

# 行 列 条件
print('行 列 条件:')
print(df[df['c']>=10])

#  行 列 条件,每个条件要用小括号!!!
print('行 列 条件:')
print(df.loc[(df['a']>2) & (df['c']>10)])
print(df.loc[(df.index>2) & (df['c']>10)])

#  行 列 条件,每个条件要用小括号!!!,选择列
print('行 列 条件:')
print(df.loc[(df.index>2) & (df['c']>10),['a','d']])

結果は次のとおりです。

按行:
      a   b   c   d
idx                
3     8   9  10  11
4    12  13  14  15
按列:
      a   c
idx        
1     0   2
2     4   6
3     8  10
4    12  14
5    16  18
按列条件查询:
      a   b   c   d
idx                
3     8   9  10  11
4    12  13  14  15
5    16  17  18  19
按列条件查询,指定列:
      a   d
idx        
3     8  11
4    12  15
5    16  19
按索引查询:
      a   b   c   d
idx                
5    16  17  18  19
按索引查询,指定列:
      b   c   a
idx            
5    17  18  16
行 列 条件:
      a   b   c   d
idx                
3     8   9  10  11
4    12  13  14  15
5    16  17  18  19
行 列 条件:
      a   b   c   d
idx                
4    12  13  14  15
5    16  17  18  19
      a   b   c   d
idx                
4    12  13  14  15
5    16  17  18  19
行 列 条件:
      a   d
idx        
4    12  15
5    16  19

11. ilocメソッド

# iloc

mydict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 },
          {'a': 10000, 'b': 20000, 'c': 30000, 'd': 40000 },]
df = pd.DataFrame(mydict)
print(df)

print(df.iloc[[0]])
print()

print(df.iloc[0])

print(df.iloc[[0,1,3]])
print()
# 按行,0行,2行; 按列, 1列,3列 ,可以间隔 'b' 'd' 列
print(df.iloc[[0, 2], [1, 3]])

# 按行,1到3行,不含3行,1,2行; 按列,1到2列,不含2列 ,'b'列
print(df.iloc[1:3, 1:2])

結果は次のとおりです。

  a      b      c      d
0      1      2      3      4
1    100    200    300    400
2   1000   2000   3000   4000
3  10000  20000  30000  40000
   a  b  c  d
0  1  2  3  4

a    1
b    2
c    3
d    4
Name: 0, dtype: int64
       a      b      c      d
0      1      2      3      4
1    100    200    300    400
3  10000  20000  30000  40000

      b     d
0     2     4
2  2000  4000
      b
1   200
2  2000

12、で

上記の例を続けると、データ df は
loc よりも効率的です。

# at ,效率高

print(df.at[3,'c'])
print(df.loc[2].at['b'])

結果は次のとおりです。

30000
2000

13.トラバース

# 按索引和行遍历dataframe
mydict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 },
          {'a': 10000, 'b': 20000, 'c': 30000, 'd': 40000 },]
df = pd.DataFrame(mydict)
# 按索引、按元素遍历
for index, row in df.iterrows():
    print('index:' + str(index))
    print('a:' + str(row['a']))
    print('b:' + str(row['b']))
    print('c:' + str(row['c']))
    print('d:' + str(row['d']))

# 按索引、按行遍历    
for rindex, row in df.iterrows():
    print('现在是第', rindex, '行')
    print(row)
    
# 按索引、按行遍历  
for rindex in df.index:
    print('现在是第', rindex, '行')
    print(df.loc[rindex])

# 按按行遍历      
for v in df.values:
    print(v)  

結果は次のとおりです。

index:0
a:1
b:2
c:3
d:4
index:1
a:100
b:200
c:300
d:400
index:2
a:1000
b:2000
c:3000
d:4000
index:3
a:10000
b:20000
c:30000
d:40000
现在是第 0 行
a    1
b    2
c    3
d    4
Name: 0, dtype: int64
现在是第 1 行
a    100
b    200
c    300
d    400
Name: 1, dtype: int64
现在是第 2 行
a    1000
b    2000
c    3000
d    4000
Name: 2, dtype: int64
现在是第 3 行
a    10000
b    20000
c    30000
d    40000
Name: 3, dtype: int64
现在是第 0 行
a    1
b    2
c    3
d    4
Name: 0, dtype: int64
现在是第 1 行
a    100
b    200
c    300
d    400
Name: 1, dtype: int64
现在是第 2 行
a    1000
b    2000
c    3000
d    4000
Name: 2, dtype: int64
现在是第 3 行
a    10000
b    20000
c    30000
d    40000
Name: 3, dtype: int64
[1 2 3 4]
[100 200 300 400]
[1000 2000 3000 4000]
[10000 20000 30000 40000]

14. MySQL を保存する

df を mysql に保存します。mysql に対応するテーブルがない可能性があります。to_sql が自動的にテーブルを作成してデータを保存します。これは非常に簡単です。

# dataframe 保存mysql数据库
from sqlalchemy import create_engine

# 按索引和行遍历dataframe
mydict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 },
          {'a': 10000, 'b': 20000, 'c': 30000, 'd': 40000 },]
df = pd.DataFrame(mydict)

engine = create_engine('mysql+pymysql://用户名:密码@IP:端口/数据库名')

conn = engine.connect()

# df看做已有的Dataframe数据,每次写入5000记录

respond = df.to_sql('test_dataframe', engine, index=False, if_exists='append', chunksize=5000)
# 返回入库记录数
print('返回入库记录数')
print (respond)

#关闭数据库连接
conn.close()

結果は次のとおりです。

返回入库记录数
4

15. インデックスを設定する

# 按索引和行遍历dataframe
mydict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 },
          {'a': 10000, 'b': 20000, 'c': 30000, 'd': 40000 },]
df = pd.DataFrame(mydict)
print (df)
df.set_index(['a'], inplace=True)
df.index.name='A'

print (df)

結果は次のとおりです。

       a      b      c      d
0      1      2      3      4
1    100    200    300    400
2   1000   2000   3000   4000
3  10000  20000  30000  40000
           b      c      d
A                         
1          2      3      4
100      200    300    400
1000    2000   3000   4000
10000  20000  30000  40000

おすすめ

転載: blog.csdn.net/qq_39065491/article/details/130805077