一句话总结:改索改名改顺序,改样改值改类型。
1.index改索引
代码如下(示例):
import pandas as pd
import numpy as np
创建数据 --------------------------------------
dict = {
'open':[1,2,3,4,5],
'high':[6,7,8,9,10],
'low':[11,12,13,14,15],
'close':[16,17,18,19,20]
}
df = pd.DataFrame(dict)
改索引 -----------------------------------------
1. index改索引
df.index = ['a','b','c','d','e'] # []列表的长度必须与df行数一致。
输出结果对比:
open high low close
0 1 6 11 16
1 2 7 12 17
2 3 8 13 18
3 4 9 14 19
4 5 10 15 20
open high low close
a 1 6 11 16
b 2 7 12 17
c 3 8 13 18
d 4 9 14 19
e 5 10 15 20
2. 将某列改为索引
代码如下(示例):
改索引 --------------------------------------
2. 将某列改为索引
df = df.set_index("close") # 将"close"列设为索引(默认同时删除"close"列的数据)
df = df.set_index("close", drop = False) # drop=False 表示保留原先"close"列的数据。(默认为True)
输出结果对比:
open high low close
0 1 6 11 16
1 2 7 12 17
2 3 8 13 18
3 4 9 14 19
4 5 10 15 20
open high low
close
16 1 6 11
17 2 7 12
18 3 8 13
19 4 9 14
20 5 10 15
1. columns 方法
代码如下(示例):
改列名 ------------------------------------------
1. columns 方法
df.columns = ('a','high','c','close')
输出结果对比:
open high low close
0 1 6 11 16
1 2 7 12 17
2 3 8 13 18
3 4 9 14 19
4 5 10 15 20
a high c close
0 1 6 11 16
1 2 7 12 17
2 3 8 13 18
3 4 9 14 19
4 5 10 15 20
2. rename 方法
代码如下(示例):
改列名 ------------------------------------------
2. rename 方法
df.rename(columns={'close':'D'},inplace=True)
输出结果:
open high low close
0 1 6 11 16
1 2 7 12 17
2 3 8 13 18
3 4 9 14 19
4 5 10 15 20
open high low D
0 1 6 11 16
1 2 7 12 17
2 3 8 13 18
3 4 9 14 19
4 5 10 15 20
代码如下(示例):
改列的顺序 ---------------------------------------
df = df[['low','close','high','open']]
输出结果对比:
open high low close
0 1 6 11 16
1 2 7 12 17
2 3 8 13 18
3 4 9 14 19
4 5 10 15 20
low close high open
0 11 16 6 1
1 12 17 7 2
2 13 18 8 3
3 14 19 9 4
4 15 20 10 5
1. Styler.applymap:逐元素
2. Styler.apply:列/行/表方式
1. 改具体某个值
1. 改具体某个值
df.iloc[2,2] = 5
df.loc[2,'low'] = 5 # 两种方法效果一样
输出结果对比:
open high low close
0 1 6 11 16
1 2 7 12 17
2 3 8 13 18
3 4 9 14 19
4 5 10 15 20
open high low close
0 1 6 11 16
1 2 7 12 17
2 3 8 5 18
3 4 9 14 19
4 5 10 15 20
2.按条件改
按条件改:将'open'列中所有大于3的数修改成0
df['open'][df['open'] > 3] = 0
输出结果对比:
open high low close
0 1 6 11 16
1 2 7 12 17
2 3 8 13 18
3 4 9 14 19
4 5 10 15 20
open high low close
0 1 6 11 16
1 2 7 12 17
2 3 8 13 18
3 0 9 14 19
4 0 10 15 20
1. 修改某一列的数据类型
df[‘low’] = df[‘low’].astype(‘int64’) # 修改’low’列为 int类型
2. 修改多列的数据类型
df[[‘low’, ‘close’]] = df[[‘low’, ‘close’]].apply(pd.to_numeric)
#内置函数,to_numeric() 可以将一列转换为数值类型,自动判断是 int 还是 float
Original: https://blog.csdn.net/m0_65167078/article/details/122196121
Author: m0_65167078
Title: pandas速学系列四:修改dataframe的六大方法
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/755236/
转载文章受原作者版权保护。转载请注明原作者出处!