DataFrame
去重drop_duplicates
参考:官方文档-pandas.DataFrame.drop_duplicates
参数:
subset:按照subset指定的列进行去重,默认为所有列;
keep:{‘first’, ‘last’, False},保留first或last,如果为False,则删除所有重复记录;
- 创建DataFrame
df_tmp = pd.DataFrame({
'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
'style': ['cup', 'cup', 'cup', 'pack', 'pack'],
'rating': [4, 4, 3.5, 15, 5]
})
"""
>>> df_tmp
brand style rating
0 Yum Yum cup 4.0
1 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0
"""
- 不加参数使用,去除所有字段都重复的记录
>>> df_tmp.drop_duplicates()
brand style rating
0 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0
- 加上subset参数,默认保留第一个重复记录
>>> df_tmp.drop_duplicates(subset="brand")
brand style rating
0 Yum Yum cup 4.0
2 Indomie cup 3.5
加载parquet文件
import pandas as pd
# 读取parquet文件
df = pd.read_parquet('file.parquet')
还可以使用pyarrow:
import pyarrow.parquet as pq
# 读取parquet文件
table = pq.read_table('file.parquet')
# 将数据转换为pandas DataFrame
df = table.to_pandas()
加载XLSX文件报错
df = pd.read_excel("test.xlsx", engine='openpyxl')
ValueError: Value must be either numerical or a string containing a wildcard
参考网址:openpyxl Value must be either numerical or a string containing a wildcard
openpyxl 在 3.1.0 之后版本引入了一个新的 bug,具体问题可以参考 issue-1959。一旦你使用的 Excel 文件中的通配符(wildcard) 不存在数字的话,就会上述错误。
- 方法一:将 openpyxl 的版本回到到 3.0.10 即可解决
pip install openpyxl==3.0.10
亲测可用(2023.5.17)
计算ctr时曝光数为0
有4种处理方式:
法1(不推荐):巨慢,跑760w个数据需要1min
def cal_rate(pv1, pv2):
"""
pv1:点击数,pv2曝光数
"""
if pv2 == 0:return 0
return pv1/pv2
df2['ctr'] = df2.apply(lambda col: cal_rate(col['click_pv'], col['expose_pv']), axis=1)
法2(不推荐):慢,跑760w个数据需要3.5s
df2['ctr'] = [x[0]/x[1] if x[1]!=0 else 0
for x in zip(df2.click_pv, df2.expose_pv)]
法3:快,跑760w个数据需要76ms
# 如果click_pv!=0,expose_pv=0,结果为inf
# 如果click_pv=0,expose_pv=0,结果为np.nan
df2["ctr"] = (df2.click_pv/df2.expose_pv) \
.replace([float('inf'), float('-inf'), np.nan], 0)
法4:快,跑760w个数据需要41ms
df2['ctr'] = np.where(df2['expose_pv']==0, 0, df2['click_pv']/df2['expose_pv'])
计算特征在指定分组下的min-max归一化
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
d1 = {"cate":["A","A","A","B","B","C","C","C"],
"score":[-3,2,4,1,3,-2,5,-1]}
df1 = pd.DataFrame(d1)
grouped = df1.groupby('cate')
# 法1
scaler = MinMaxScaler()
## scaler.fit_transform是对每一列进行norm,因此需要shape=(-1,1)
## transform需要1-d的数据,因此需要flatten()
grouped['score'].transform(lambda x: scaler.fit_transform(x.values.reshape(-1,1)).flatten())
# 法2
grouped['score'].transform(lambda x:(x-x.min())/(x.max()-x.min()))