Skip to content

python pandas数据修改

0 背景

对数据的修改、增加和删除在数据清洗的过程中经常发生。因此本文主要利用pandas对数据修改。

1 使用

初始化数据

image-20231226232524490

在WPS中初始化数据:

df = xl("$A$1:$G$18", headers=True, sheet_name="工作表1")
# 设置索引为uid列
df.set_index('uid',inplace=True)
print(df.head())

在python中初始化数据:

data = {  
    "uid": [1, 2, 3, 4, 5, 6, 7, 8, 9],  
    "uname": ["雷嘉伦", "杜睿", "孙晓明", "方宇宁", "彭睿", "苏詩涵", "宋子异", "彭震南", "钟宇宁"],  
    "usex": ["男", "男", "男", "男", "男", "女", "男", "男", "男"],  
    "uage": [79, 83, 19, 31, 18, 71, 47, 55, 59],  
    "umail": ["lj712@mail.com", "ruidu@hotmail.com", "xiaomsun@gmail.com", "", "pengrui910@icloud.com", None, "ziyso@gmail.com", "zhepeng404@gmail.com", "yuningzhong407@hotmail.com"],  
    "ucity": ["洛杉矶", "广州市", "纽约", "深圳", "纽约", "东莞", "中山", "阿克伦", "芝加哥"],  
    "udate": ["2001/11/13", "2002/5/7", "2010/8/9", "2018/12/17", "2017/4/3", "2021/1/20", "2001/6/18", "2016/2/17", "2014/3/15"]  
}
df = pd.DataFrame(data)
df.set_index('uid', inplace=True)

修改数值

df.loc[0, 'uage']

df.loc[0, 'uage'] = 30

df.iloc[0, 2] = 34

修改范围内的值

# 修改范围内的值
df[df['ucity'] == '广州市'] = '广州'

批量修改, 使用同样形状的数据来修改值

ucity = ['深圳'] * df.shape[0]
df['ucity'] = ucity

批量替换

# 批量替换
df.loc[3:5, 'uname':'uage']

df2 = pd.DataFrame([
    {'uname': '杜睿', 'usex': '男', 'uage': 34},
    {'uname': '孙晓明', 'usex': '男', 'uage': 23},
    {'uname': '方宇宁', 'usex': '男', 'uage': 12},
    {'uname': '彭睿', 'usex': '男', 'uage': 18}
    ])

df.loc[3:5, 'uname':'uage'] = df2

其他形式的替换数据

# 替换数据

# 将数据中所有的55替换成10
df.replace(55,10)
# 将0~3全换成5
df.replace([0, 1, 2, 3], 5)
# 对应替换
df.replace([0, 1, 2, 3], [4, 3, 2, 1])

# 向下填充, `bfill`是将值修改填充为下一行的值, 有{'pad', 'ffill', 'bfill', `None`}可选, `ffill`是前向填充
s = pd.Series([1,2,3,4,2,3])
s.replace([2,4],method='ffill')

# 对应字典修改
df.replace({0: 10, 1: 100})

# 将指定字段的指定值修改为100
df.replace({'ucity': '深圳', 'uname': '1'}, '100')

# 将指定列里的指定值替换其他值
df.replace({'ucity': {'中山': '中山市', '深圳': '深圳市'}})

# 使用正则表达式
df.replace(to_replace=r'^.*?@gmail.com$', value='orange@orange.com', regex=True)

df.replace({'umail': r'^.*?@gmail.com$'}, {'A': 'orange@orange.com'}, regex=True)

df.replace(regex={r'^.*?@gmail.com$': 'orange@orange.com', 'foo': 'abc'})
df.replace(regex=[r'^.*?@gmail.com$', r'^.*?@apple.com$'], value='orange@orange.com')

空值填充

# 空值填充

# 将空值填充为0
df.fillna(0)

# 前向填充, 将空值填为上一个的值, 有{'bfill', 'pad', 'ffill', None}可选
df.fillna(method='ffill')

# 为各列填充不同的值
values = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
df2.fillna(value=values) 
# 只替换第一个
df2.fillna(value=values, limit=1)

索引修改

# 对列名 表头进行重命名
df.rename(columns={'uname':'user_name'})

# 对索引进行重命名
df.rename(index={0: "x", 1: "y", 2: "z"})

# 对索引类型进行修改
df.rename(index=str) 
# 传入索引类型, 进行修改
df.rename(str.lower, axis='columns')

df.rename({1: 2, 2: 4}, axis='index')

2 关于

欢迎关注我的微信公众号