1、将下面字典创建为DataFrame
data = {"grammer":["Python","C","Java","GO",np.nan,"SQL","PHP","Python"],
"score":[1,2,np.nan,4,5,6,7,10]}
df = pd.DataFrame(data)
2、提取含有字符串Python的行
df[df['grammer'] == 'Python']
3、输出df的所有列名
df.columns
4、修改第二列列名为'popularity'
df.rename(columns={'score':'popularity'},inplace = True)
# inplace:是否原地替换。布尔值,默认为False。如果为True,则在原DataFrame上进行操作,返回值为None。
5、统计grammer列中每种编程语言出现的次数
df['grammer'].value_counts()
6、将空值用上下值的平均值填充
df['popularity'] = df['popularity'].fillna(df['popularity'].interpolate())
#fillna(method参数控制向上还是向下填充,ffill:向下自动填充,bfill:向上自动填充)
7、提取popularity列中值大于3的行
df[df['popularity'] > 3]
8、按照grammer列进行去除重复值
df.drop_duplicates(['grammer'])
9、计算popularity列平均值
df['popularity'].mean()
10、将grammer列转换为list
df['grammer'].to_list()
11、将DataFrame保存为EXCEL
df.to_excel('test.xlsx')
12、查看数据行列数
df.shape
13、提取popularity列值大于3小于7的行
df[(df['popularity'] > 3) & (df['popularity'] < 7)]
14、交换两列位置
temp = df['popularity']
df.drop(labels=['popularity'],axis=1,inplace=True)
df.insert(0,'popularity',temp)
15、提取popularity列最大值所在行
df[df['popularity'] == df['popularity'].max()]
16、查看最后5行数据
df.tail()
17、删除最后一行数据
df.drop([len(df)-1],inplace=True)
18、添加一行数据
row = {'grammer':'Perl','popularity':6.6}
df = df.append(row,ignore_index=True)
19、对数据按照popularity列值的大小进行排序
df.sort_values("popularity",inplace=True)
20、统计grammer列每个字符串的长度
df['grammer'] = df['grammer'].fillna('R')
df['len_str'] = df['grammer'].map(lambda x: len(x))