pandas的简单例子

pandas的简单例子

标签(空格分隔): pandas


#-*- coding: utf-8 -*-
import pandas as pd

s = pd.Series([1,2,3], index=['a','b','c'])
d = pd.DataFrame([[1,2,3],[4,5,6]], columns = ['a','b','c'])
d2 = pd.DataFrame(s)

>>> d.head()
   a  b  c
0  1  2  3
1  4  5  6
>>> d.describe()
             a        b        c
count  2.00000  2.00000  2.00000
mean   2.50000  3.50000  4.50000
std    2.12132  2.12132  2.12132
min    1.00000  2.00000  3.00000
25%    1.75000  2.75000  3.75000
50%    2.50000  3.50000  4.50000
75%    3.25000  4.25000  5.25000
max    4.00000  5.00000  6.00000
### Python Pandas 简单代码示例 #### 创建并操作 DataFrame 创建一个简单的 `DataFrame` 是使用 Pandas 进行数据分析的基础: ```python import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['New York', 'Los Angeles', 'Chicago']} df = pd.DataFrame(data) print(df) ``` 这段代码展示了如何通过字典来构建一个包含姓名、年龄和城市的数据框[^1]。 #### 数据类型的转换 有时需要改变列中的数据类型,这可以通过 `.astype()` 方法实现: ```python df['Age'] = df['Age'].astype(str) print(df.dtypes) ``` 此段代码将 Age 列由整数型转为了字符串型[^2]。 #### 比较两个 DataFrame 中对应位置上的元素是否不同 如果想要比较两组数据之间的差异,则可以利用 `.ne()` 函数来进行逐项对比: ```python other_data = {'Name': ['Alice', 'Bobby', 'Chris'], 'Age': [25, 31, 40], 'City': ['Boston', 'San Francisco', 'Seattle']} other_df = pd.DataFrame(other_data) comparison = df.ne(other_df) print(comparison) ``` 这里显示了怎样判断原始数据帧与其他数据帧之间各字段值的不同之处[^3]。 #### 将 DataFrame 导出到 Excel 文件 最后一步通常是把处理好的表格保存下来供后续查看或分享给他人。下面的例子说明了怎么设置日期格式并将结果存入 Excel 表格中: ```python with pd.ExcelWriter('output.xlsx', date_format='YYYY-MM-DD') as writer: df.to_excel(writer, sheet_name='Sheet1') ``` 上述命令会按照指定的时间样式导出当前工作区内的数据至名为 output.xlsx 的电子表格文档里[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值