简体   繁体   English

Python -- Function 以 Pandas dataframe 作为参数

[英]Python -- Function with a Pandas dataframe as an argument

I have to create a function that takes a Pandas dataframe as an argument and returns a copy of the dataframe after replacing the null values in each column with the most frequent value in the column.我必须创建一个 function,它将 Pandas dataframe 作为参数,并在用列中最频繁的值替换每列中的 null 值后返回 dataframe 的副本。

Cannot use FOR or WHILE loops.不能使用FORWHILE循环。

Well, to create a copy you can simply use df.copy(deep = True) (note that deep = True creates a new dataframe-object, otherwise you get a reference to the copied dataframe).那么,要创建一个副本,您可以简单地使用df.copy(deep = True) (请注意,deep = True 创建一个新的数据框对象,否则您将获得对复制的数据框的引用)。 To replace the null values with the most frequent values, you can use the mode method for Series and DataFrames ( https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.mode.html ).要用最频繁的值替换 null 值,您可以对 Series 和 DataFrames 使用模式方法 ( https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.mode.html )。

An example would be: df = df.fillna(df.mode().iloc[0])一个例子是: df = df.fillna(df.mode().iloc[0])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM