Pandas数据框架中的转换函数
Python是一种进行数据分析的伟大语言,主要是因为以数据为中心的Python包的奇妙生态系统。Pandas就是这些包中的一个,它使数据的导入和分析变得更加容易。
将一个pandas对象转换为一个指定的dtype
DataFrame.astype()函数用于将pandas对象转换为指定的dtype。 astype()函数也提供了将任何合适的现有列转换为分类类型的能力。
代码#1:转换Weight列的数据类型。
# importing pandas as pd
import pandas as pd
# Making data frame from the csv file
df = pd.read_csv("nba.csv")
# Printing the first 10 rows of
# the data frame for visualization
df[:10]
由于数据中有一些 “纳米 “值,为了避免任何错误,我们将放弃所有含有纳米值的行。
# drop all those rows which
# have any 'nan' value in it.
df.dropna(inplace = True)
# let's find out the data type of Weight column
before = type(df.Weight[0])
# Now we will convert it into 'int64' type.
df.Weight = df.We<strong>ight.astype('int64')
# let's find out the data type after casting
after = type(df.Weight[0])
# print the value of before
before
# print the value of after
after
输出:
# print the data frame and see
# what it looks like after the change
df
为输入对象列推断更好的数据类型
DataFrame.infer_objects()函数试图为输入对象列推断更好的数据类型。该函数尝试对对象类型的列进行软转换,而不对非对象和不可转换的列进行改变。推断规则与正常的系列/数据框架构建期间相同。
代码#1:使用infer_objects()函数来推断更好的数据类型。
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":["sofia", 5, 8, 11, 100],
"B":[2, 8, 77, 4, 11],
"C":["amy", 11, 4, 6, 9]})
# Print the dataframe
print(df)
输出 :
让我们看看数据框架中每一列的dtype(数据类型)。
# to print the basic info
df.info()
正如我们在输出中看到的,第一列和第三列是对象类型的,而第二列是int64类型的。现在将数据框架切片,并从中创建一个新的数据框架。
# slice from the 1st row till end
df_new = df[1:]
# Let's print the new data frame
df_new
# Now let's print the data type of the columns
df_new.info()
输出 :
正如我们在输出中看到的,列 “A “和 “C “是对象类型的,尽管它们包含整数值。所以,让我们试试infer_objects()函数。
# applying infer_objects() function.
df_new = df_new.infer_objects()
# Print the dtype after applying the function
df_new.info()
输出 :
现在,如果我们看一下每一列的dtype,我们可以看到 “A “和 “C “列现在是int64类型。
检测缺失值
DataFrame.isna()函数用于检测缺失值。它返回一个布尔同尺寸的对象,表明这些值是否是NA。NA值,如None或numpy.NaN,会被映射为True值。其他的都会被映射为假值。空字符串 “或numpy.inf等字符不被视为NA值(除非你设置pandas.options.mode.use_inf_as_na = True)。
代码#1:使用isna()函数来检测数据帧中的缺失值。
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.read_csv("nba.csv")
# Print the dataframe
df
让我们使用isna()函数来检测缺失的值。
# detect the missing values
df.isna()
输出 :
在输出中,对应于缺失值的单元格包含真值,否则为假值。
检测现有的/非遗漏的价值
DataFrame.notna()函数检测数据框架中现有的/非缺失的值。该函数返回一个布尔对象,其大小与应用该函数的对象相同,表明每个单独的值是否是na值。所有的非缺失值都被映射为真,缺失值被映射为假。
代码#1:使用notna()函数来查找数据框中所有的非缺失值。
# importing pandas as pd
import pandas as pd
# Creating the first dataframe
df = pd.DataFrame({"A":[14, 4, 5, 4, 1],
"B":[5, 2, 54, 3, 2],
"C":[20, 20, 7, 3, 8],
"D":[14, 3, 6, 2, 6]})
# Print the dataframe
print(df)
让我们使用dataframe.notna()函数来找到数据框中所有的非遗漏值。
# find non-na values
df.notna()
输出 :
正如我们在输出中看到的,数据框架中所有的非缺失值都被映射为真。由于数据框架中没有缺失值,所以没有假值。
DataFrame中的转换方法
功能 | 说明 |
---|---|
DataFrame.convert_objects() | 试图为对象列推断更好的dtype。 |
DataFrame.copy() | 返回此对象的索引和数据的副本。 |
DataFrame.bool() | 返回单个元素PandasObject的bool。 |