python版本:3.6.2
编辑器:jupyter notebook
完整代码如下:
import numpy as np
import pandas as pd
df = pd.read_excel('D:\\python_test\\num.xls')
df.sort_values(by=['Number'])# 按Number列排序
# 使用merge函数实现excel表格的合并,合并方式为inner
df_inner = pd.merge(df, df1, how='inner')
#设置索引列
df.set_index('id')
# 使用where对数据进行判断和分组,并使用group字段进行标记
df['group'] = np.where(df['Number'] > 50, 'high', 'low')# where条件语句:添加group列,若Number>50则为high,否则为low
# 对符合多个条件的数据进行分组标记
df.loc[(df['Author2'] == '刘宏伟') & (df['Number'] >= 50), 'sign']=1# 对Author2列等于刘宏伟且Number列大于等于50的数据标记为1
# 取单行数据
df.loc[1]
# 按索引区域提取
df.loc[0:5]
print(df)
运行结果截图:
# group和sign标记后

# df.loc[1]

# df.loc[0:5]

补充:
# 条件筛选
df.loc[df['Number']== 51,['Author2','Number']]

可能出现的报错1:报错798: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison result = getattr(x, name)(y)
可能出现的报错2:TypeError: invalid type comparison
无效。。。因为之前把51加了引号。。。‘51’为无效类型。。。只有str类型才加引号,例如'张三’。论基础知识的重要性......
# 条件筛选
df.loc[(df['Number']>66) | (df['Author2']== '刘宏伟'),['Author2','Number']]

# 条件筛选并排序
df.loc[(df['Number']>66) | (df['Author2']== '刘宏伟'),['Author2','Number']].sort(['Number'])

悲剧来了,报错了。。。AttributeError: 'DataFrame' object has no attribute 'sort'
【解决方案】把sort改为sort_values

# 将所筛选字段Number列求和
df.loc[(df['Number']>66) | (df['Author2']== '刘宏伟'),['Author2','Number']].sort_values(['Number']).Number.sum()

# 将所筛选字段Number列计数
df.loc[(df['Number']>66) | (df['Author2']== '刘宏伟'),['Author2','Number']].sort_values(['Number']).Number.count()




DataFrame的增删查改



# 随机采样
df.sample(n=3)
# 对数据表进行描述性统计,小数位为2,并进行转置
df.describe().round(2).T
# 输出为excel格式
df.to_excel('D:\\python_test\\num.xlsx', sheet_name='practice')
# 输出为csv文件
df.to_csv('D:\\python_test\\num.csv')
网友评论