文章目录
notebook配上pandas简直效率神器
整理下日常用到的pandas的知识点
1. description
描述
.count()
获取数据的整体汇总.dtypes
获取值类型.head(10)
.tail(20)
dataframe某一列的描述
df[col].value_counts()
df.groupby([col]).size()
2. 创建 dataframe
df = pd.DataFrame([['a1', 1], ['a2', 4]], columns=['uid', 'score'])
df = pd.DataFrame({'col1': np.arange(3), 'col2': np.arange(5, 8)})
data = data.applymap(str) df所有列转为str
字典的形式比较常用
3. dataframe 去重
df[column].unique()
drop_duplicated(subset=[''])
去重dropna(subset=[''])
去空值
dropna详细用法
data.dropna(how = 'all')
# 传入这个参数后将只丢弃全为缺失值的那些行data.dropna(axis = 1)
# 丢弃有缺失值的列(一般不会这么做,这样会删掉一个特征)data.dropna(axis=1,how="all")
# 丢弃全为缺失值的那些列data.dropna(axis=0,subset = ["Age", "Sex"])
# 丢弃‘Age’和‘Sex’这两列中有缺失值的行
4. 针对df某一列处理
df[column].apply(lambda x: )
对series的列做出计算等
当然也可以传入整行dfdf.apply(lambda x: x[column1])
df[1]=df[2].map(str)+df[3].map(str)
将两列非字符串合并
5. 合并两个df
-
pd.merge(self,other how='',on='')
合并两个表
建议参考 [Python3]pandas.merge用法详解 -
all_df.append(a_df,ignore_index=True)
-
pd.concat(all_list,axis=0,ignore_index=True)
传入df的list
6. 选择某几行
df.loc[(df[0]==1) & (df[1]==2)]
df.loc[(df[0]==1) & (df[1]==2), [0,1,2]] # 选择0,1,2列
7. 聚合
groupby('')[''].size()
聚合并对某一列做statsgroupby('').agg({:})
groupby('').apply(lambda x:x.str.cat(sep=':'))
聚合并做字符串连接
7.1 排序
每一个col1组内排序
df = df.groupby('col1', sort=False)\
.apply(lambda x:x.sort_values("col2", ascending=False))\
.reset_index(drop=True)
如果想要获取排序后的值
df['排名'] = df.groupby('col1',axis=0)['col2'].rank(ascending=False)
注意:聚合会产生multi-index,我们在reset_index
可能会遇到index与column重合的情况,这时我们可以rename column,这样就可以继续reset_index
.
8. 按行遍历
4种方式
# 法1
for index, row in df.iterrows():
print(row["c1"], row["c2"])
# 法2
for row in df.itertuples(index=True, name='Pandas'):
print(getattr(row, "c1"), getattr(row, "c2"))
# 法3 这种方法常用于生成新的列
def valuation_formula(x, y):
return x * y * 0.5
df['price'] = df.apply(lambda row: valuation_formula(row['x'], row['y']), axis=1)
# 法4 根据索引遍历
for i in range(0, len(df)):
print df.iloc[i]['c1'], df.iloc[i]['c2']
9. 分组计数
df['binned'] = pd.cut(df['values'], bins)
bin_counts = df['binned'].value_counts()
10.列转行
# 使用 explode 方法分割列表
df[column_to_explode] = df[column_to_explode].str.split(delimiter)
df_new = df.explode(column_to_explode).reset_index(drop=True)
在pandas中遍历DataFrame行
andas.DataFrame实现分组、排序并且为分组插入排名
Python之dataframe按照某一列分组并排序,同时加上排名