如下所示:
1
2
3
4
5
6
|
python 设置值
import pandas as pd
import numpy as np
dates = pd.date_range( '20180101' ,periods = 6 )
df = pd.DataFrame(np.arange( 24 ).reshape( 6 , 4 ),index = dates,columns = [ 'A' , 'B' , 'C' , 'D' ])
print (df)
|
1
2
3
4
5
6
7
|
A B C D
2018 - 01 - 01 0 1 2 3
2018 - 01 - 02 4 5 6 7
2018 - 01 - 03 8 9 10 11
2018 - 01 - 04 12 13 14 15
2018 - 01 - 05 16 17 18 19
2018 - 01 - 06 20 21 22 23
|
1
2
|
df.loc[ '20180102' , 'A' ] = 1111
print (df)
|
1
2
3
4
5
6
7
|
A B C D
2018 - 01 - 01 0 1 2 3
2018 - 01 - 02 1111 5 6 7
2018 - 01 - 03 8 9 10 11
2018 - 01 - 04 12 13 14 15
2018 - 01 - 05 16 17 18 19
2018 - 01 - 06 20 21 22 23
|
1
2
|
df.iloc[ 2 , 2 ] = 2222
print (df)
|
1
2
3
4
5
6
7
|
A B C D
2018 - 01 - 01 0 1 2 3
2018 - 01 - 02 1111 5 6 7
2018 - 01 - 03 8 9 2222 11
2018 - 01 - 04 12 13 14 15
2018 - 01 - 05 16 17 18 19
2018 - 01 - 06 20 21 22 23
|
1
2
|
df[df.A> 12 ] = 0 #修改df数据中符合条件的所有值
print (df)
|
1
2
3
4
5
6
7
|
A B C D
2018 - 01 - 01 0 1 2 3
2018 - 01 - 02 0 0 0 0
2018 - 01 - 03 8 9 2222 11
2018 - 01 - 04 12 13 14 15
2018 - 01 - 05 0 0 0 0
2018 - 01 - 06 0 0 0 0
|
1
2
|
df.A[df.A< 4 ] = 11 #修改df数据中A列符合条件的所有值
print (df)
|
1
2
3
4
5
6
7
|
A B C D
2018 - 01 - 01 11 1 2 3
2018 - 01 - 02 11 0 0 0
2018 - 01 - 03 8 9 2222 11
2018 - 01 - 04 12 13 14 15
2018 - 01 - 05 11 0 0 0
2018 - 01 - 06 11 0 0 0
|
1
2
|
df[ 'F' ] = np.nan
print (df)
|
1
2
3
4
5
6
7
|
A B C D F
2018 - 01 - 02 11 0 0 0 NaN
2018 - 01 - 03 8 9 2222 11 NaN
2018 - 01 - 04 12 13 14 15 NaN
2018 - 01 - 05 11 0 0 0 NaN
2018 - 01 - 06 11 0 0 0 NaN
|
1
|
print (np. any (df.isnull()) = = True ) #isnull检测是否含有NaN值,有就返回True。np.any()检测df数据中是否含有等于Ture的值
|
1
|
True
|
NaN值填充:print(df.fillna(value=0))
以上这篇python设置值及NaN值处理方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/knowmore0823/article/details/79060370