给选定的位置赋另外的值
import pandas as pd
import numpy as np
dates = pd.date_range('20130101', periods =6)
df = pd.DataFrame(np.arange(24).reshape((6,4)),index=dates,columns = ['A','B','C','D'])
print(df)
A B C D
2013-01-01 0 1 2 3
2013-01-02 4 5 6 7
2013-01-03 8 9 10 11
2013-01-04 12 13 14 15
2013-01-05 16 17 18 19
2013-01-06 20 21 22 23
按位置或标签修改值
df.iloc[2,2] = 111 # 位置
df.loc['20130101','B'] = 222 # 标签
print(df)
A B C D
2013-01-01 0 222 2 3
2013-01-02 4 5 6 7
2013-01-03 8 9 111 11
2013-01-04 12 13 14 15
2013-01-05 16 17 18 19
2013-01-06 20 21 22 23
按条件修改值
针对A列>8,修改整个DataFrame
df.A[df.A > 8] = 0
print(df)
A B C D
2013-01-01 0 222 2 3
2013-01-02 4 5 6 7
2013-01-03 8 9 111 11
2013-01-04 0 0 0 0
2013-01-05 0 0 0 0
2013-01-06 0 0 0 0
针对A列>8,只修改A列
df.A[df.A > 8] = 0
print(df)
A B C D
2013-01-01 0 222 2 3
2013-01-02 4 5 6 7
2013-01-03 8 9 111 11
2013-01-04 0 13 14 15
2013-01-05 0 17 18 19
2013-01-06 0 21 22 23
针对A列>8,修改B列的值
df.B[df.A > 8] = 0
print(df)
A B C D
2013-01-01 0 222 2 3
2013-01-02 4 5 6 7
2013-01-03 8 9 111 11
2013-01-04 12 0 14 15
2013-01-05 16 0 18 19
2013-01-06 20 0 22 23
增加列
新增空列
df['F'] = np.nan
print(df)
A B C D F
2013-01-01 0 222 2 3 NaN
2013-01-02 4 5 6 7 NaN
2013-01-03 8 9 111 11 NaN
2013-01-04 12 0 14 15 NaN
2013-01-05 16 0 18 19 NaN
2013-01-06 20 0 22 23 NaN
增加其他列,保持index统一
df['E'] = pd.Series(np.arange(1,7),index = df.index)
print(df)
A B C D F E
2013-01-01 0 222 2 3 NaN 1
2013-01-02 4 5 6 7 NaN 2
2013-01-03 8 9 111 11 NaN 3
2013-01-04 12 0 14 15 NaN 4
2013-01-05 16 0 18 19 NaN 5
2013-01-06 20 0 22 23 NaN 6
网友评论