Python数据操作集合汇总

创建dataframe
df=pd.DataFrame([[list1],[list2]...].T,index=['list1','list2'])

dataframe 改变列名
方法一

df.columns=['names','scores']

方法二 reindex以及reindex_like
index是行 columns是列

df.reindex(index=['c', 'f', 'b'], columns=['three', 'two', 'one'])
df.reindex(['c', 'f', 'b'], axis='index')
df.reindex_like(df2)

方法三 rename

movies_df.rename(columns={
'Runtime (Minutes)': 'Runtime',
'Revenue (Millions)': 'Revenue_millions'
}, inplace=True)

df.rename(columns={'one': 'foo', 'two': 'bar'},
index={'a': 'apple', 'b': 'banana', 'd': 'durian'})

dataframe 排序
df.sort_values(by=['list1','list2'],ascending=True)

df.sort_values(by="grade")

列表推导式
%整除,zip函数的使用

[x for x in range(1.8) if x%2==0]

a={x:y for x,y in zip(range(1,7),'abcdef')}

重复repeat
ls=[1,2,3,4]
ls*2 # 方法一
sorted(ls*2)
np.repeat(ls,2) #方法二

查看dataframe变量信息
movies_df.info()

查看dataframe维度
movies_df.shape

dataframe去掉重复
temp_df =temp_df.drop_duplicates(inplace=True,keep=False)

dataframe描述
movies_df['genre'].describe()

dataframe按列计数
movies_df['genre'].value_counts()

dataframe切片操作
字典不可以切片 需要自取

df[0:3] #选择行
df["A"] #选择列
df.loc #selection by label
df.iloc #selection by position
df.at #快速选择
df.iat

根据条件判断进行切片选择

df[df > 0]
df[df.A > 0]

isin判断 %in%
isin

df2[df2['E'].isin(['two', 'four'])]

movies_df[movies_df['director'].isin(['Christopher Nolan', 'Ridley Scott'])].head()

根据isin取反

~movies_df['director'].isin(['Christopher Nolan', 'Ridley Scott'])

赋随机值
df.loc[:, 'D'] = np.random.randint(0, 7, size=10)

根据条件在数字前加负号
df2[df2 > 0] = -df2

去掉缺失值
df1.dropna(how='any')

apply的lambda操作
df.apply(lambda x: x.max() - x.min()) lambda x:x if/for....

movies_df["rating_category"] = movies_df["rating"].apply(lambda x: 'good' if x >= 8.0 else 'bad')

dataframe的竖直拼接rbind操作
df.append(s, ignore_index=True) #方法一
pieces = [df[:3], df[3:7], df[7:]] #方法二
pd.concat(pieces)


mergy 合并
pd.merge(left, right, on='key')

类似aggregate的分类合计
df.groupby(['A', 'B']).sum()

dataframe多列合并为一列 stack操作
stacked = df2.stack()

python pivot_table 数据透视表
pd.pivot_table(df, values=‘D’, index=[‘A’, ‘B’], columns=[‘C’])

python 改变变量类型 astype
df["grade"] = df["raw_grade"].astype("category") # as.factor
dft[['a', 'b']] = dft[['a', 'b']].astype(np.uint8)


dataframe删除列 drop
df.drop(['a', 'd'], axis=0)

dataframe删除行 参考dataframe切片操作

计算dataframe相关系数corelation
movies_df.corr()

多重判断选择 或判断 操作or %in%
movies_df[(movies_df['director'] == 'Christopher Nolan') | (movies_df['director'] == 'Ridley Scott')].head()

返回判断索引 which where操作
方法一
a = df[(df.BoolCol==3)&(df.attr==22)].index.tolist()
df['names'].tolist().index('random') #返回第一个
方法二
np.where()
np.where(df['names']=='random') #返回所有

方法三 索引切片
df.loc[df['names']=='random','scores']


判断索引 根据值比较大小
vframe.scores>float(vframe.loc[vframe['names']=='random','scores'])
vframe.loc[vframe.scores>float(vframe.loc[vframe['names']=='random','scores']),'names']
df.a>df.a[df.b==1].iloc[0]


list to pandas series
x_label_update=pd.Series(x_label_update)


原文链接:https://blog.csdn.net/weixin_37973876/article/details/106185093

原文地址:https://www.cnblogs.com/LQZ888/p/13177830.html