0
点赞
收藏
分享

微信扫一扫

Pandas练习题50道

  1. 导入 Pandas 库并简写为 pd,并输出版本号
import pandas as pd
pd.__version__
  1. 从列表创建 Series
import numpy as np
import pandas as pd

temp = np.arange(0, 6)
data = pd.Series(temp)
print(data)

  1. 从字典创建 Series
import numpy as np
import pandas as pd

temp = {'a': 1,
        'b': 3}
data = pd.Series(temp)
print(data)
  1. NumPy 数组创建 DataFrame
import numpy as np
import pandas as pd

temp = np.arange(0,6)
data = pd.DataFrame(temp, index=['a', 'b', 'c', 'd', 'e', 'f'], 
                    columns=['temp'])
print(data)
  1. CSV中创建 DataFrame,分隔符为,编码格式为gbk
df = pd.read_csv('test.csv', encoding='gbk, sep=';')
  1. 从字典对象data创建DataFrame,设置索引为labels
import numpy as np
import pandas as pd

data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],
        'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],
        'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}

labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

df = pd.DataFrame(data, index=labels)
print(df)
  1. 显示DataFrame的基础信息,包括行的数量;列名;每一列值的数量、类型
print(df.info())
  1. 展示df的前3行
print(df.head(3))
  1. 取出dfanimalage
print(df[['animal', 'age']])
  1. 取出索引为[3, 4, 8]行的animalage
print(df.loc[df.index[[3, 4, 8]], ['animal', 'age']])
  1. 取出’age’值大于3的行
print(df[df.age>3])
  1. 取出age值缺失的行
print(df[df.age.isnull()])
  1. 取出age在2,4间的行
print(df[(df.age >= 2) & (df.age <= 4)])
  1. f行的age改为1.5
df.loc['f','age'] = 1.5
print(df)
  1. 计算visits的总和
print(df['visits'].sum())
  1. 计算每个不同种类animalage的平均数
print(df.groupby('animal')['age'].mean())
  1. 计算df中每个种类animal的数量
print(df['animal'].value_counts())
  1. 先按age降序排列,后按visits升序排列
df.sort_values(by=['age', 'visits'], ascending=[False, True])
print(df)
  1. priority列中的yes, no替换为布尔值True, False
df['priority'] = df['priority'].map({'yes': True, 'no': False})
print(df)
  1. animal列中的snake替换为python
df['animal'] = df['animal'].replace('snake', 'python')
print(df)
  1. .对每种animal的每种不同数量visits,计算平均age,即,返回一个表格,行是aniaml种类,列是visits数量,表格值是行动物种类列访客数量的平均年龄
举报

相关推荐

0 条评论