Python数据分析与统计建模实战

1、Read in data from a CSV-file with a header (‘.\Data\data_kaplan\swim100m.csv’). Also show the first 5 data points.

可以使用 Python 的 pandas 库来完成此任务,示例代码如下:

import pandas as pd

# 读取 CSV 文件
data = pd.read_csv('.\Data\data_kaplan\swim100m.csv')

# 展示前 5 个数据点
print(data.head())

2、读取一个MS - Excel文件(’.\Data\data_others\Table 2.8 Waist loss.xls’),并展示最后五个数据点。

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

import pandas as pd
# 读取Excel文件
inFile2 = '.\Data\data_others\Table 2.8 Waist loss.xls'
xls = pd.ExcelFile(inFile2)
data = xls.parse('Sheet1', skiprows=2)
# 展示最后五个数据点
print(data.tail())

3、读取压缩文件 http://cdn.crcpress.com/downloads/C9500/GLM_data.zip 中的 MS - Excel 文件。

可以使用如下代码实现从指定的压缩文件中读取 Excel 文件:

import numpy as np
import pandas as pd
import urllib
import io
import zipfile

def getDataDobson(url, inFile):
    # get the zip - archive
    GLM_archive = urllib.request.urlopen(url).read()
    # make the archive available as a byte - stream
    zipdata = io.BytesIO()
    zipdata.write(GLM_archive)
    # extract the requested file from the archive, as a pandas XLS - file
    myzipfile = zipfile.ZipFile(zipdata)
    xlsfile = myzipfile.open(inFile)
    # read the xls - file into Python, using Pandas, and return the extracted data
    xls = pd.ExcelFile(xlsfile)
    df = xls.parse('Sheet1', skiprows = 2)
    return df

url = r'http://cdn.crcpress.com/downloads/C9500/GLM_data.zip'
inFile = r'GLM_data/Table 2.8 Waist loss.xls'
df = getDataDobson(url, inFile)
print(df.tail())

4、生成一个 Pandas DataFrame,x 列是从 0 到 10 秒、采样率为 10 Hz 的时间戳,y 列是频率为 1.5 Hz 的正弦数据值,z 列是对应的余弦值。将 x 列标记为“Time”,y 列标记为“YVals”,z 列标记为“ZVals”。

import numpy as np
import pandas as pd

dt = 0.1  # 10 Hz 采样率,时间间隔为 0.1 秒
omega = 2 * np.pi * 1.5  # 1.5 Hz 的角频率
t = np.arange(0, 10, dt)
y = np.sin(omega * t)
z = np.cos(omega * t)
df = pd.DataFrame({'Time': t, 'YVals': y, 'ZVals': z})

5、显示这个DataFrame的前几行。

在代码中,通过以下语句显示DataFrame的前5行:print(df.head())

6、从“Yvals”和“ZVals”列中提取第10 - 15行的数据,并将其写入文件“out.txt”。

以下是实现该操作的代码:

import numpy as np
import pandas as pd

# Generate the data
t = np.arange(0, 10, 0.1)
y = np.sin(2 * np.pi * 1.5 * t)
z = np.cos(2 * np.pi * 1.5 * t)

# Assemble them in a DataFrame
df = pd.DataFrame({'Time': t, 'YVals': y, 'ZVals': 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值