1. 创建DateFrame:
(1)字典法:
data = {"grammer":['Python', 'C', 'Java', 'GO', np.NaN, 'SQL', 'PHP', 'Python'],
"score":[1.0, 2.0, np.NaN, 4.0, 5.0, 6.0, 7.0, 10.0]}
df = pd.DataFrame(data)
df
(2)Series:
pd.DataFrame(pd.Series(np.random.randint(1, 10, 100)), columns = ['xxx'])
(3)先生成dataframe,再加入列
frame = pd.DataFrame()
frame['ID'] = Series
(4)以现有的dataframe列新建一个dataframe:
df_new = pd.DataFrame(columns = df.columns.tolist())
2. Numpy:
(1)随机生成20个0-100的随机整数:Numpy.random.randint()
np.random.randint(0, 100, 20)
(2)生成20个0-100固定步长的数:Numpy.arange()
np.arange(0, 100, 5)
# np.arange()函数分为一/两/三个参数三种情况:
# 1)一个参数时,参数值为终点,起点取默认值0,步长取默认值1。
# 2)两个参数时,第一个参数为起点,第二个参数为终点,步长取默认值1。
# 3)三个参数时,第一个参数为起点,第二个参数为终点,第三个参数为步长。其中步长支持小数
(3)生成20个指定分布(如标准正态分布)的数:Numpy.random.normal()
np.random.normal(0, 1, 20)
(4)提取第一列中可以整除5的数字位置:Numpy.argwhere()
np.argwhere(np.array(df['col1'] % 5 == 0))
(5)查看两列值相等的行号:Numpy.where()
#方法一:值相等
df[df['xxx1'] == df['xxx2']].index
#方法二:np.where()
np.where(df.xxx1 == df.xxx2)
#np.where()用法:
# np.where(condition, x, y): # 满足条件(condition),输出x,不满足输出y。
# np.where(condition):
# 只有条件 (condition),没有x和y,则输出满足条件 (即非0) 元素的坐标 (等价于numpy.nonzero)。当条件成立时,where返回的是每个符合condition条件元素的坐标,返回的是以元组的形式。
#相关资料:
# https://www.cnblogs.com/massquantity/p/8908859.html
# https://blog.csdn.net/lens___/article/details/83896645
(6)查找第一列的局部最大值位置:Numpy.sign()
#思路:查找比它前一个和后一个数字都大数字
tem = np.diff(np.sign(np.diff(df['col1'])))
np.where(tem == -2)[0] + 1
(7)对第二列计算移动平均值:Numpy.convolve()
np.convolve(df['col2'], np.ones(3)/3, mode='valid')
#参考资料:https://blog.csdn.net/u011599639/article/details/76254442
(8)计算两列欧式距离:Numpy.linalg.norm()
#方法一:公式法
import math as mt
mt.sqrt(sum((df['col2']-df['col3'])**2))
#方法二:numpy函数
np.linalg.norm(df['col2'] - df['col3'])
(9)查找某列数据中第三大值的行号:Numpy.argsort()
#方法一:
df['xxx'].argsort()[::-1][len(df)-3]
#注:argsort() -- 从小到大排, 输出索引;[[::-1]]倒序输出 -- 即为从大到小排;
#方法二:先进行倒序排序,然后重置索引,取第三行第一列即为第3大值的行号
df['data'].sort_values(ascending=False).reset_index().iloc[2,0]
(10)一些统计基础函数:
补充:
log(x + 1):np.log1p
以2为底的对数:np.log2
e的x次幂-1:np.expm1
e的次数幂:np.exp
取对数:np.log
开根号:np.sqrt
平方:np.exp2