DataFrame使用总结1(超实用)

DataFrame使用总结1(超实用):

1. 合并两个表

frame = [df1, df2]
df = pd.concat(frame)
res = pd.merge(df, df1, on=['key', 'key1'], how='inner')
res = pd.merge(df, df1, left_on=['key'], left_on=['key1'], how='inner')

合并表的操作(Merge, join, and concatenate)

http://pandas.pydata.org/pandas-docs/stable/merging.html

2. split() 和 strip() 函数

strip是删除的意思,主要是删除开头和结尾处的字符串

rm 表示要删除的字符串

  • str.strip(rm) 表示删除开头和结尾,处于rm序列中的字符(需要正确理解)
  • str.lstrip(rm) 表示删除开头,处于rm序列中的字符(需要正确理解)
  • str.rstrip(rm) 表示删除结尾,处于rm序列中的字符(需要正确理解)

当rm为空时,默认删除空白符,包含(' ', ' ', ' ', ' ')

a = '  1223ss!# '
a = a.strip()
a
>>> '1223ss!#'
b = a.strip('12')   # attention:是将开头和结尾处包含 ‘1’字符和含有‘2’字符的全部删掉
>>> '3ss!#' 
b = a.strip('21') # attentionn: 和顺序无关
>>> '3ss!#' 

split是分割的意思

a = '  1223ss!# pp '
b = a.split('#')
b
>>> ['  1223ss!', ' pp ']
# 如果我们想截取到ss,可以这样操作
b = a.split('!')[0].split('3')[1]   # 多种方法都可以取到,这里只是讲解split的用法
b
>>> 'ss'

3. list 转DataFrame

import pandas as pd
l = [[1,2,3],[1,5,4],[2,4,2]]
pd.DataFrame(l, columns=['lie_A','lie_B','lie_C'])
>>> lie_A 	lie_B 	lie_C
  0 	1 	  2    	 3
  1 	1 	  5  	 4
  2 	2 	  4  	 2


4. 读取和存储表

常用的两种表是csv和excel

读取表为DataFrame结构

table1 = pd.DataFrame(pd.read_excel('sss.xlsx'))
table2 = pd.read_csv('sss.csv')

存储表

table1.to_excel('sss.xlsx')
table2.to_csv('sss.csv', encoding='utf-8')

csv表是以 ‘,’ 为分割符,所以最好保存为csv格式

5. 将DataFrame转化为array,list

# 将table(DataFrame)的lie 
table1 = np.array(table['lie'])    # 转化为array
table2 = table1.tolist()		   # 转化为list

# 将table(DataFrame)转化为list
table1 = np.array(table)    # 转化为array
table2 = table1.tolist()		   # 转化为list

6. DataFrame中最好不要用循环,用apply,如果只能用循环处理,转化为array或者list再做处理

apply 的具体使用方法:http://www.cnblogs.com/gaoss/p/7657044.html

import pandas as pd
table1
>>>  	index 	lie0
	0 	  1 	kkk
	1 	  2 	sss
	2 	  3 	ddd
	3 	  4 	ppp
    
def tem(x):
        return x+'_hello'

table1.lie0 = table1.lie0.apply(tem)
table1
>>>  index  	lie0
  0 	1 	 kkk_hello
  1 	2 	 sss_hello
  2 	3 	 ddd_hello
  3 	4 	 ppp_hello

7. 对DataFrame重建索引

table = table.reset_index()

8. 对DataFrame删除列或者增加列

删除列:

table = table.drop(['lie0', 'lie1'], axis=1)

增加列:

table['new_lie'] = '' # 新增一个新列,列名为new_lie,值为空
table['new_lie'] = table['lie0'].astype('str') + table['lie1'].astype('str') # 将lie0和lie1的值赋给new_lie

9. 筛选数据

table = table.loc[table['lie0'] > 0]

将table表中lie0 列大于0的数据筛选出来,其他列也会跟随该列变化

10. 强制类型转换

例如 ‘lie0’ 列数据为int,需要将其转化为str,就需要用到强制类型转换

table['sku_division_code'].astype('int')

11. 对某一列列名进行重命名

将 lie0 替换为 lie1

table.rename(columns={'lie0': 'lie1'}, inplace=True)

12. get_dummies(one_hot 编码)

import pandas as pd
table1 = pd.DataFrame(pd.read_excel('sss.xlsx'))
table1
>>> index 	lie0
0 	  1 	kkk
1 	  2 	sss
2 	  3 	ddd
3 	  4 	ppp

pd.get_dummies(table1, columns=['lie0'])
>>> index 	lie0_ddd 	lie0_kkk 	lie0_ppp 	lie0_sss
0 	 1 			0 			1 			0 			0
1 	 2 			0 			0 			0 			1
2 	 3 			1 			0 			0 			0
3 	 4 			0 			0 			1 			0

13 处理日期

  1. 求两个日期中间的所有日期
a = '2017-08-04' 
b = '2017-09-01'
rng = pd.date_range(a,b)
rng
>>> DatetimeIndex(['2017-08-04', '2017-08-05', '2017-08-06', '2017-08-07',
               '2017-08-08', '2017-08-09', '2017-08-10', '2017-08-11',
               '2017-08-12', '2017-08-13', '2017-08-14', '2017-08-15',
               '2017-08-16', '2017-08-17', '2017-08-18', '2017-08-19',
               '2017-08-20', '2017-08-21', '2017-08-22', '2017-08-23',
               '2017-08-24', '2017-08-25', '2017-08-26', '2017-08-27',
               '2017-08-28', '2017-08-29', '2017-08-30', '2017-08-31',
               '2017-09-01'],
              dtype='datetime64[ns]', freq='D')

len(rng)
>>> 29

rng[1]
>>> Timestamp('2017-08-05 00:00:00', freq='D')

  1. 将str转化为日期格式
import pandas as pd
from datetime import *
a = '2017-08-04'

type(a)
>>> <type 'str'>

a = datetime.strptime(str(a), '%Y-%m-%d')
type(a)
>>> datetime.datetime
  1. 判断一天是星期几
a.weekday()
>>> 4   # 0到6代表从星期一到星期日
  1. 计算两个时间之间相差多少秒
a = '08:10:20' 
b = '15:34:43'
time_a = datetime.strptime(a, '%H:%M:%S')
time_b = datetime.strptime(b, '%H:%M:%S')
total = (time_b - time_a).seconds
total
>>> 26663

14. list 的常见操作

删除 与 增加元素

lie = ['1','2','kk','3','m']

lie.remove('kk')
lie
>>> ['1', '2', '3', 'm']

lie.insert(0, 'xx')
lie
>>> ['xx', '1', '2', '3', 'm']

lie.append('ten')
lie
>>> ['xx', '1', '2', '3', 'm', 'ten']

if 'xx' in lie:   # 判断xx在lie这个list中
  print('right')
 
>>> right

15. 空值的使用

table1
>>> index 	lie0   lie1
0 	 1  	kkk 	p1
1 	 2  	sss    	p2
2 	 3  	NaN 	p3
3 	 4  	ppp 	p4

table1[pd.isnull(table1.lie0)] = 'mmm'
table1
>>> index 	lie0   lie1
0 	 1  	kkk 	p1
1 	 2  	sss    	p2
2 	 3  	mmm 	p3
3 	 4  	ppp 	p4

16 将表头(列名)取出来,为list

lieming = list(table1.columns.values)
>>> [u'index', u'lie0', u'lie1']
lieming = table1.columns.values.tolist()
>>> [u'index', u'lie0', u'lie1']

17. zfill()

a = '301'    # 将字符串填充为4位
a.zfill(4)
>>> '0301'

18. stack && unstack

>>> 
   col1 col2
a	1	2
b	1	2

stack = df.stack()
a  col1    1
   col2    2
b  col1    1
   col2    2

stack.unstack()

   col1 col2
a	1	2
b	1	2

19. 其他

table1.shape
>>>(4,3)
x = table1.shape[0]
y = table1.shape[1]
x
>>> 4
y
>>> 3

table1.describe()  # 显示基础信息 
>>>	    index
count 	4.000000
mean 	2.500000
std 	1.290994
min 	1.000000
25% 	1.750000
50% 	2.500000
75% 	3.250000
max 	4.000000
原文地址:https://www.cnblogs.com/gaoss/p/7800899.html