学校图书馆组织的一个讲座,感觉有点小儿科,不如马普所非平衡统计物理的第 10 讲来得系统和深入,只不过用的是 python 而不是 R。

pd.Series.astype(): 数据类型转换

data["Income"] = pd.to_numeric(data["Income"], errors='coerce')

第一次知道 pd.Series.astype(str)pd.Series.astype(”string”) 给出的结果不同。前者对 pandas 来说仍是 object,后者是 pandas 可以识别的数据类型。

pd.Series.replace(): 数据替换

data['City_Corrected'] = data['City'].replace(to_replace = 'U City', value = "University City") # the original column 'City' stays the same

修正的数据写入新 column 而不是取代原数据~~,值得学习~~(刚表扬完就开始 inplace=True 了)

在数字字符串前面补 0

data_combined['phys_zip_str'] = data_combined['Physical ZIP'].astype("string")
data_combined['phys_zip_str_5'] = data_combined['phys_zip_str'].str.zfill(5)

依据复杂判据,截取数据

|, 且 &, 非 !

居然完全没讲 .loc[].iloc[]

正则表达式

import re
pattern = re.compile('^(.*?) Ronald(.)')
data.City.replace(to_replace=pattern, value="iLuo", regex=True, inplace=True)

合并两个 pd.DataFrame

之前我的做法:

df1.set_index(['key1','key2','key3'],inplace=True)
df2.set_index(['key1','key2','key3'],inplace=True)
df1['df2-key4'] = df2['key4']
df1['df2-key5'] = df2['key5']
# ...

本次培训的做法:

data_with_demographic = pd.merge(data, demographic_data, on='Zip', how='left')
data_with_demographic
Screenshot from 2024-03-01 11-34-48.png
Screenshot from 2024-03-01 11-34-48.png

Inference: 作为合并索引列的名字~~必须相同(?)。~~如果名字不同的话,需要制定 left_on, right_on 两个参数

合并可以用多个列作为索引吗?可以,on=[’k1’,’k2’]

本文收录于以下合集: