对dataframe的行和列进行遍历和修改

首先先定一个这样的字典,然后我们用不同的方法对其遍历和修改

字典df

df=pd.DataFrame({"A":[1,2,3,4],"B":[5,6,7,8],"C":[1,1,1,1]})
   A  B  C
0  1  5  1
1  2  6  1
2  3  7  1
3  4  8  1

i.遍历列

1.ix函数(df.ix[条件,操作区域])

df.ix[df.A>1,'B']=-1
df
   A  B  C
0  1  5  1
1  2 -1  1
2  3 -1  1
3  4 -1  1

2.iterrows()函数。这个函数一般跟index和row一起使用,应为他会返回两个值,一个就是index,一个是行

for index,row in df.iterrows():
	if row['A']>1:
		row['B']=-1
   A  B  C
0  1  5  1
1  2 -1  1
2  3 -1  1
3  4 -1  1

3.where函数,np.where(条件,then,else)

df["then"]=np.where(df.A<3,1,0)
df
   A  B  C  then
0  1  5  1     1
1  2  6  1     1
2  3  7  1     0
3  4  8  1     0

4.apply函数你可以对行或列每一个数值进行自己指定函数的操作

def judgeLevel(df):
    if df['A'] < 2:
        return 'C'
    elif df['A'] > 3:
        return 'A'
    else:
        return 'B'

 df['level']=df.apply(lambda r:judgeLevel(r),axis=1)
 df
   A  B  C   level
0  1  5  1    C
1  2  6  1    B
2  3  7  1    B
3  4  8  1    A

ii.遍历列
iloc函数

for i in range(0, len(df)):
    print (df.iloc[i]['A'], df.iloc[i]['B'])
     1 5
     2 6
     3 7
     4 8

猜你喜欢

转载自blog.csdn.net/starmoth/article/details/84779622