dataframe操作
1.去除重复项drop_duplication
#去除重复项drop_duplication import pandas as pd df = pd.DataFrame({"col1":[1, 1, 2, 2], "col2" : ["a", "a", "b", "b"]}) print(df) #指定某个列,保留第一出现的元素 df.drop_duplicates("col1", "first", inplace=True) print(df) df = pd.DataFrame({"col1":[1, 1, 2, 2], "col2" : ["a", "a", "b", "b"]}) print(df) #对某一列进行去除 df = df["col1"].drop_duplicates() print(df)
col1 col2 0 1 a 1 1 a 2 2 b 3 2 b
col1 col2 0 1 a 2 2 b
col1 col2 0 1 a 1 1 a 2 2 b 3 2 b
0 1 2 2 Name: col1, dtype: int64
2.设置索引
#设置索引 import pandas as pd df = pd.DataFrame({"col1":[1, 1, 2, 2], "col2" : ["a", "a", "b", "b"]}) df.set_index("col1", inplace=True) print(df) df.index.name = "索引" print(df) df = pd.DataFrame({"col1":[1, 1, 2, 2], "col2" : ["a", "a", "b", "b"]}) index = df.pop("col1") df.index = index df.index.name = "索引" print(df)
col2 col1 1 a 1 a 2 b 2 b
col2 索引 1 a 1 a 2 b 2 b
col2 索引 1 a 1 a 2 b 2 b
3.round操作
发现该操作只能把小数点位数减少,而不能够把小数点位数变多.比如小数点后3位的可以round成小数点后2位,反之则不可以.
可以用applymap来增加小数点的位数,但是对所有的列进行的操作.只针对某列的还有找到.
df = pd.DataFrame({"a":[1,2.0,3], "b":[4,5.0,6]}, columns = ["a", "b"]) df = df.applymap(lambda x : "%.3f" % x)
a b 0 1.000 4.000 1 2.000 5.000 2 3.000 6.000
新战场:https://blog.csdn.net/Stephen___Qin