Excel对于处理和计算少量数据非常有用,但是日常工作中能自动化,少动手,就更舒服了,对吧?
因此,建议使用大熊猫Pandas。:-)
接下来,为了诙谐起见,会经常把pandas叫熊猫,大家知道就好。
Pandas是Python的数据处理包,它可以编写为一个程序,可以读取和处理表格数据,如Excel文件和CSV,处理它并聚合它,然后输出它。此外,即使您没有开发环境,也可以立即在Google提供的Collaboration的免费开发环境中进行尝试。
还有一份声明称微软正在考虑采用新的脚本语言来取代自Office 98以来Office 98以来尚未更新的VBA。
Microsoft认为,Excel中的Excel支持。
首先尝试抓住pandas的全貌
在Pandas中,一维数据称为Series,二维是DataFrame,三维是Panel。DataFrame相当于Excel中的表或数据透视表。Pandas官方备忘单的将帮助您全面了解情况。以下是下面链接的材料的图像。
翻译官方熊猫备忘单
熊猫秘笈
以下是以下文章的部分摘录:
在Pandas中演示的常见Excel任务
添加摘要列
首先,将链接的 excel数据加载到pandas DataFrame中。
import pandas as pd
import numpy as np
df = pd.read_excel("excel-comp-data.xlsx")
df.head()
如果通过head()获得存储为DataFrame的前5行df,则如下所示。
account name street city state postal-code Jan Feb Mar
0 211829 Kerluke, Koepp and Hilpert 34456 Sean Highway New Jaycob Texas 28752 10000 62000 35000
1 320563 Walter-Trantow 1311 Alvis Tunnel Port Khadijah NorthCarolina 38365 95000 45000 35000
2 648336 Bashirian, Kunde and Price 62184 Schamberger Underpass Apt. 231 New Lilianland Iowa 76517 91000 120000 35000
3 109996 D’Amore, Gleichner and Bode 155 Fadel Crescent Apt. 144 Hyattburgh Maine 46021 45000 120000 10000
4 121213 Bauch-Goldner 7274 Marissa Common Shanahanchester California 49681 162000 120000 35000
现在考虑添加“Jan”,“Feb”和“Mar”的总列“total”的情况。在Excel中,您将添加sum(G2:I2)列,如下图所示。
另一方面,在熊猫中,它写如下。
df["total"] = df["Jan"] + df["Feb"] + df["Mar"]
df.head()
添加摘要行
现在考虑查找每列总和的情况。对于Excel,需要为要汇总的每列输入SUM(G2:G16)的描述。
如果是熊猫,可以写成如下。
df["Jan"].sum(), df["Jan"].mean(),df["Jan"].min(),df["Jan"].max()
(1462000, 97466.666666666672, 10000, 162000)
或者您可以通过编写如下的方式将结果检索为系列。
sum_row=df[["Jan","Feb","Mar","total"]].sum()
sum_row
Jan 1462000
Feb 1507000
Mar 717000
total 3686000
dtype: int64
虽然此时sum_row的类型是Series,但将其转换为DataFrame的类型并对其进行转置使其成为一行表。
df_sum=pd.DataFrame(data=sum_row).T
df_sum
Jan Feb Mar total
0 1462000 1507000 717000 3686000
将之前找到的df_sum与df列相关联。然后df_sum将处于以下内部状态。※NaN表示Excel中的#N / A.
df_sum=df_sum.reindex(columns=df.columns)
df_sum
account name street city state postal-code Jan Feb Mar total
0 NaN NaN NaN NaN NaN NaN 1462000 1507000 717000 3686000
最后,您可以按如下方式组合df和df_sum:
df_final=df.append(df_sum,ignore_index=True)
df_final.tail()
以下显示组合df_final的最后5行的tail()。
account name street city state postal-code Jan Feb Mar total
11 231907 Hahn-Moore 18115 Olivine Throughway Norbertomouth NorthDakota 31415 150000 10000 162000 322000
12 242368 Frami, Anderson and Donnelly 182 Bertie Road East Davian Iowa 72686 162000 120000 35000 317000
13 268755 Walsh-Haley 2624 Beatty Parkways Goodwinmouth RhodeIsland 31919 55000 120000 35000 210000
14 273274 McDermott PLC 8917 Bergstrom Meadow Kathryneborough Delaware 27933 150000 120000 70000 340000
15 NaN NaN NaN NaN NaN NaN 1462000 1507000 717000 3686000
喜欢这篇文章吗?接下来需要什么高级技巧,可以留言!希望能有更多的朋友加入pythoner团体。