我通宵翻譯Pandas官方文檔,寫了這一份Excel萬字肝貨操作!
回復(fù)“書籍”即可獲贈Python從入門到進(jìn)階共10本電子書
大家好,我是黃同學(xué)
本文翻譯自Pandas官方文檔! 文末有驚喜,看到最后你不虧!
閱讀須知
import pandas as pd
import numpy as np
數(shù)據(jù)結(jié)構(gòu)
1. 通用術(shù)語翻譯

2. DataFrame
3. Series
4. Index
A1:Z1,而在 Pandas 中,您可以使用population.loc['Chicago']。5. 副本與就地操作
sorted_df = df.sort_values("col1")
df = df.sort_values("col1")
df.sort_values("col1", inplace=True)
數(shù)據(jù)輸入和輸出
1. 利用值構(gòu)造一個數(shù)據(jù)框DataFrame
df = pd.DataFrame({"x": [1, 3, 5], "y": [2, 4, 6]})
df

2. 讀取外部數(shù)據(jù)
CSV
url = ("https://raw.github.com/pandas-dev/pandas/master/pandas/tests/io/data/csv/tips.csv")
tips = pd.read_csv(url)
tips

tips = pd.read_csv("tips.csv", sep="\t", header=None)
# 或者,read_table 是帶有制表符分隔符的 read_csv 的別名
tips = pd.read_table("tips.csv", header=None)
Excel文件
tips.to_excel("./tips.xlsx")
tips_df = pd.read_excel("./tips.xlsx", index_col=0)
3. 限制輸出
tips.head(5)

4. 導(dǎo)出數(shù)據(jù)
數(shù)據(jù)操作
1. 列操作
tips["total_bill"] = tips["total_bill"] - 2
tips["new_bill"] = tips["total_bill"] / 2
tips

2. 過濾

tips[tips["total_bill"] > 10]

is_dinner = tips["time"] == "Dinner"
is_dinner.value_counts()
tips[is_dinner]

3. If/then邏輯
=IF(A2 < 10, "low", "high")的公式,將其拖到新存儲列中的所有單元格。
tips["bucket"] = np.where(tips["total_bill"] < 10, "low", "high")
tips

4. 日期功能

tips["date1"] = pd.Timestamp("2013-01-15")
tips["date2"] = pd.Timestamp("2015-02-15")
tips["date1_year"] = tips["date1"].dt.year
tips["date2_month"] = tips["date2"].dt.month
tips["date1_next"] = tips["date1"] + pd.offsets.MonthBegin()
tips["months_between"] = tips["date2"].dt.to_period("M") - tips["date1"].dt.to_period("M")
tips[["date1", "date2", "date1_year", "date2_month", "date1_next", "months_between"]]

5. 列的選擇
隱藏列; 刪除列; 引用從一個工作表到另一個工作表的范圍;
保留某些列
tips[["sex", "total_bill", "tip"]]

刪除某些列
tips.drop("sex", axis=1)

重命名列
tips.rename(columns={"total_bill": "total_bill_2"})

6. 按值排序

tips = tips.sort_values(["sex", "total_bill"])
tips

字符串處理
1. 查找字符串長度
=LEN(TRIM(A2))
tips["time"].str.len()
tips["time"].str.rstrip().str.len()

2. 查找子串的位置

tips["sex"].str.find("ale")

3. 按位置提取子串
=MID(A2,1,1)
tips["sex"].str[0:1]

4. 提取第n個單詞
firstlast = pd.DataFrame({"String": ["John Smith", "Jane Cook"]})
firstlast["First_Name"] = firstlast["String"].str.split(" ", expand=True)[0]
firstlast["Last_Name"] = firstlast["String"].str.rsplit(" ", expand=True)[0]
firstlast

5. 大小寫轉(zhuǎn)換
firstlast = pd.DataFrame({"string": ["John Smith", "Jane Cook"]})
firstlast["upper"] = firstlast["string"].str.upper()
firstlast["lower"] = firstlast["string"].str.lower()
firstlast["title"] = firstlast["string"].str.title()
firstlast

合并
df1 = pd.DataFrame({"key": ["A", "B", "C", "D"], "value": np.random.randn(4)})
df2 = pd.DataFrame({"key": ["B", "D", "D", "E"], "value": np.random.randn(4)})


inner_join = df1.merge(df2, on=["key"], how="inner")
left_join = df1.merge(df2, on=["key"], how="left")
right_join = df1.merge(df2, on=["key"], how="right")
outer_join = df1.merge(df2, on=["key"], how="outer")

查找值不需要是查找表的第一列; 如果匹配多行,則每個匹配都會有一行,而不僅僅是第一行; 它將包括查找表中的所有列,而不僅僅是單個指定的列; 它支持更復(fù)雜的連接操作;
其他注意事項
1. 填充柄
df = pd.DataFrame({"AAA": [1] * 8, "BBB": list(range(0, 8))})
series = list(range(1, 5))
df.loc[2:5, "AAA"] = series
df

2. 刪除重復(fù)項
df = pd.DataFrame({
"class": ["A", "A", "A", "B", "C", "D"],
"student_count": [42, 35, 42, 50, 47, 45],
"all_pass": ["Yes", "Yes", "Yes", "No", "No", "Yes"]})
df.drop_duplicates()
df.drop_duplicates(["class", "student_count"])

3. 數(shù)據(jù)透視表

pd.pivot_table(
tips,
values="tip",
index=["size"],
columns=["sex"],
aggfunc=np.average)

4. 添加一行
df
new_row = {"class": "E", "student_count": 51, "all_pass": True}
df.append(new_row, ignore_index=True)

5. 查找和替換
tips
tips == "Sun"
tips["day"].str.contains("S")

tips.replace("Thu", "Thursday")

------------------- End -------------------
往期精彩文章推薦:

歡迎大家點贊,留言,轉(zhuǎn)發(fā),轉(zhuǎn)載,感謝大家的相伴與支持
想加入Python學(xué)習(xí)群請在后臺回復(fù)【入群】
萬水千山總是情,點個【在看】行不行
/今日留言主題/
隨便說一兩句吧~~
評論
圖片
表情
