1、创建DataFrame
1.1 random.randint
temp=np.random.randint(0,100,20)
print(temp)
df1=pd.DataFrame(temp)
print(df)
1.2 np.arange
df2=pd.DataFrame(np.arange(0,100,5))
1.3 random.normal
df3=pd.DataFrame(np.random.normal(0,1,20))
2、用concat合并新DataFrame
axis参数,0表示按行合并,1表示按列合并;ignore_index=True,自动填充列名和索引列
df=pd.concat([df1,df2,df3],axis=1,ignore_index=True)
df=pd.concat([df1,df2,df3],axis=0,ignore_index=True)
3、 修改列名
df.columns=['col1','col2','col3']
print(df)
4、提取第一列和第二列都出现的数据
反逻辑,用~,表示第一列有,但第二列没有的数字
df_new=df['col1'][~df['col1'].isin(df['col2'])]
df_new=df['col1'][df['col1'].isin(df['col2'])]
5、统计一col1列中值出现的次数
df4=df['col1'].value_counts()
df5=df['col1'].value_counts().index[:3]
6、np.where
a = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
print(a)
print(a[:,1])
[[1 2]
[3 4]
[5 6]
[7 8]]
[2 4 6 8]
7、::-1
df=df.iloc[:,::-1]
是Pandas DataFrame的一个操作,用于翻转(反转)整个DataFrame。
iloc
是Pandas的索引操作,它基于整数位置进行索引。
:
表示选择所有行,
::-1
表示选择所有列并按照-1的步长进行反转,也就是从最后一列到第一列。
8、提取指定行的内容
iloc和take都可实现
df_new=df['col1'].iloc[[1,3,5]]
df_new1=df['col1'].take([1,3,5])
9、按行求均值,注意axis参数
df[['col1','col3']].mean(axis=1)
10、满足条件的内容被替换为指定内容
df['col1'][df['col1']>20]='high'
df.col1[df['col1']>20]='high'
np.sign()
用于返回数组中各元素的符号。对于正数,它返回1,对于负数,它返回-1,对于零,它返回0。例如,对于一个一维数组 [1, -3, 2, 0, -5]
,使用 np.sign()
函数会返回 [1, -1, 1, 0, -1]
。