python pandas学习笔记¶
reshape¶
- 描述:
更改dataframe的数据维度
- 备注:
-1 代表指定后剩余的
numpy和dataframe使用方法类似
- 示例:
[10]:
import numpy as np
array = np.array(np.arange(12))
print('shape of array:\n', array.shape)
array_reshape = array.reshape(3,4)
print('shape of array_reshape: \n', array_reshape.shape)
array_reshape_1 = array.reshape(4,-1)
print('shape of array_shape_1:\n', array_reshape_1.shape)
shape of array:
(12,)
shape of array_reshape:
(3, 4)
shape of array_shape_1:
(4, 3)
pandas.Index, columns, set_names¶
- 描述:
index:指定行索引
columns:指定列索引,并指定行索引列名
- 参考链接:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.html
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.set_names.html
- 示例:
[29]:
import pandas as pd
b = np.array(np.arange(12)).reshape(3,4)
df = pd.DataFrame(b, index = ['A','B','C'],
columns = pd.Index(['a','b','c','d']
,name = 'index_name'))
print('df:\n',df)
df.columns = ['a_r','b_r','c_r','d_r']
print('columns after rename :\n',df.columns)
df.index.set_names('index_rename', inplace = True)
print('rename index name :\n', df)
df:
index_name a b c d
A 0 1 2 3
B 4 5 6 7
C 8 9 10 11
columns after rename :
Index(['a_r', 'b_r', 'c_r', 'd_r'], dtype='object')
rename index name :
a_r b_r c_r d_r
index_rename
A 0 1 2 3
B 4 5 6 7
C 8 9 10 11
python2 pandas连接mysql¶
import MySQLdb
conn=MySQLdb.connect(host= host, user = username, passwd=password,
port = port, db = db, charset='utf-8')
df = pd.read_sql(sql, conn, index_col="id")
[ ]: