pandas设置值

pandas设置值:

import pandas as pd
import numpy as np

dates = pd.date_range('20190529', periods=4)
df = pd.DataFrame(np.arange(16).reshape((4, 4)), index=dates, columns=['A', 'B', 'C', 'D'])

# 根据索引修改
df.iloc[2, 2] = 888
print(df)
"""
                A   B    C   D
2019-05-29   0   1    2   3
2019-05-30   4   5    6   7
2019-05-31   8   9  888  11
2019-06-01  12  13   14  15
"""

# 根据行和列修改
df.loc['20190530', 'B'] = 666
print(df)
"""
                A    B    C   D
2019-05-29   0    1    2   3
2019-05-30   4  666    6   7
2019-05-31   8    9  888  11
2019-06-01  12   13   14  15
"""

# 条件选择数据修改
df[df.A > 10] = 0
print(df)
"""
               A    B    C   D
2019-05-29  0    1    2   3
2019-05-30  4  666    6   7
2019-05-31  8    9  888  11
2019-06-01  0    0    0   0
"""
df.C[df.C > 10] = 0
print(df)
"""
               A    B  C   D
2019-05-29  0    1  2   3
2019-05-30  4  666  6   7
2019-05-31  8    9   0  11
2019-06-01  0    0   0   0
"""

df['E'] = np.NAN
print(df)
"""
            A    B  C   D   E
2019-05-29  0    1  2   3 NaN
2019-05-30  4  666  6   7 NaN
2019-05-31  8    9  0  11 NaN
2019-06-01  0    0  0   0 NaN
"""

df['F'] = pd.Series([1, 2, 3, 4], index=pd.date_range('20190529', periods=4))
print(df)
"""
                A    B  C   D   E  F
2019-05-29  0    1  2   3 NaN  1
2019-05-30  4  666  6   7 NaN  2
2019-05-31  8    9  0  11 NaN  3
2019-06-01  0    0  0   0 NaN  4
"""
最后修改:2019 年 05 月 29 日 01 : 59 PM
如果觉得我的文章对你有用,请随意赞赏

发表评论