Python编程与数据分析实践示例

1、创建一个函数,使其作为一个简单的计算器。如果未指定运算,默认为加法。如果运算指定错误,返回一条提示消息。例如:calc(4, 5, “multiply”) 返回 20;calc(3, 5) 返回 8;calc(1, 2, “something”) 返回错误消息。

以下是实现该功能的 Python 代码:

def calc(a, b, operation='add'):
    if operation == 'add':
        return a + b
    elif operation == 'subtract':
        return a - b
    elif operation == 'multiply':
        return a * b
    elif operation == 'divide':
        if b != 0:
            return a / b
        else:
            return 'Error: division by zero'
    else:
        return 'Error: invalid operation specified'

2、给定一个数字列表,编写两个函数,一个函数用于返回一个新列表,其中所有相邻的重复元素都被缩减为单个元素;另一个函数用于返回一个新列表,移除列表中所有重复值(无论相邻与否)。示例:对于列表 [1, 2, 2, 3, 2],第一个函数应返回 [1, 2, 3, 2],第二个函数应返回 [1, 2, 3]。

在 Python 中,可使用以下代码实现:

# 移除相邻重复元素
def remove_adjacent_duplicates(lst):
    if not lst:
        return []
    result = [lst[0]]
    for num in lst[1:]:
        if num != result[-1]:
            result.append(num)
    return result

# 移除所有重复元素
def remove_all_duplicates(lst):
    return list(set(lst))

# 测试示例
lst = [1, 2, 2, 3, 2]
print(remove_adjacent_duplicates(lst))  # 输出: [1, 2, 3, 2]
print(remove_all_duplicates(lst))       # 输出: [1, 2, 3]

3、1. 创建一个名为Employee的类,构造函数提供两个属性:name(姓名)和years_of_service(服务年限)。有一个名为salary的方法,其计算方式为1500 + 100 * 服务年限。2. 创建一个名为Manager的子类,重新定义salary方法为2500 + 120 * 服务年限。3. 创建一个类似字典的小型数据库,键为员工姓名。用以下实例填充数据库:samples = [Employee(‘lucy’, 3), Employee(‘john’, 1), Manager(‘julie’, 10), Manager(‘paul’, 3)]。4. 返回一个由姓名和薪水组成的表格,即一个包含列表的列表[[姓名, 薪水]]。5. 计算平均薪水。

以下是实现上述需求的Python代码:

class Employee:
    def __init__(self, name, years_of_service):
        self.name = name
        self.years_of_service = years_of_service

    def salary(self):
        return 1500 + 100 * self.years_of_service


class Manager(Employee):
    def salary(self):
        return 2500 + 120 * self.years_of_service

samples = [Employee('lucy', 3), Employee('john', 1), Manager('julie', 10), Manager('paul', 3)]
database = {sample.name: sample for sample in samples}
result_table = [[sample.name, sample.salary()] for sample in samples]
total_salary = sum([sample.salary() for sample in samples])
average_salary = total_salary / len(samples)
print(result_table)
print(average_salary)

代码中定义了 Employee 类和 Manager 子类,创建了数据库,生成了表格并计算了平均薪水。

4、给定数组:X = np.random.randn(4, 2) (一个4行2列的随机正态分布数组)。找出每列中最小值所在的行索引。

可使用 np.argmin(X, axis = 0) 来找出每列中最小值所在的行索引。

5、如何打印数据框的列名

可以使用

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值