Pandas中的元素替换
生活随笔
收集整理的這篇文章主要介紹了
Pandas中的元素替换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
# 序列中的元素替換
ser = pd.Series([0, 1, 2, 3, 4, 5])
print(ser.replace(0, 6)) # 單個元素替換
print(ser.replace([0, 1, 2, 3, 4, 5], [5, 4, 3, 2, 1, 0])) # 列表替換
print(ser.replace({1: 11, 2: 22})) # 字典替換# DataFram中的元素替換
df = pd.DataFrame({"a": [1, 2, 3, 4, 5], "b": [6, 7, 8, 9, 10]})
# 1.單個元素替換
print(df.replace(10, 0))
# 2.列表替換
print(df['a'].replace([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]))
# 3.字典替換
movie_map = dict(zip(df['b'], range(len(df['b']))))
df['b'] = df['b'].replace(movie_map)) # 適合數據量小的時候
df['b'] = [movie_map[i] for i in df['b']] # 適合數據量大的時候處理
# 4.多列不同值替換為相同值
print(df.replace({'a': 1, 'b': 6}, np.nan))
# 5.插值法替換
print(df['a'].replace([1, 2, 3], method='pad'))
# 6.用元素在列表中的索引替換
l = [6, 5, 1, 9, 8]
print(df['b'].replace(l, [i for i in range(len(l))]))
總結
以上是生活随笔為你收集整理的Pandas中的元素替换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: KMP算法的核心,是一个被称为部分匹配表
- 下一篇: Hystrix 简介和使用