Pyspark从数据框中的列中删除空值

时间:2017-06-23 05:38:02

标签: python hadoop apache-spark mapreduce pyspark

我的Dataframe如下所示

ID,FirstName,LastName

1,Navee,Srikanth

2,,Srikanth 

3,Naveen,

现在我的问题陈述是我必须删除第2行,因为First Name为空。

我在pyspark脚本下面使用

join_Df1= Name.filter(Name.col(FirstName).isnotnull()).show()

我收到错误

  File "D:\0\NameValidation.py", line 13, in <module>
join_Df1= filter(Name.FirstName.isnotnull()).show()
  

TypeError:'Column'对象不可调用

任何人都可以帮我解决这个问题

3 个答案:

答案 0 :(得分:5)

您的DataFrame FirstName看起来像空值而不是Null。以下是一些尝试的选项: -

df = sqlContext.createDataFrame([[1,'Navee','Srikanth'], [2,'','Srikanth'] , [3,'Naveen','']], ['ID','FirstName','LastName'])
df.show()
+---+---------+--------+
| ID|FirstName|LastName|
+---+---------+--------+
|  1|    Navee|Srikanth|
|  2|         |Srikanth|
|  3|   Naveen|        |
+---+---------+--------+

df.where(df.FirstName.isNotNull()).show() #This doen't remove null because df have empty value
+---+---------+--------+
| ID|FirstName|LastName|
+---+---------+--------+
|  1|    Navee|Srikanth|
|  2|         |Srikanth|
|  3|   Naveen|        |
+---+---------+--------+

df.where(df.FirstName != '').show()
+---+---------+--------+
| ID|FirstName|LastName|
+---+---------+--------+
|  1|    Navee|Srikanth|
|  3|   Naveen|        |
+---+---------+--------+

df.filter(df.FirstName != '').show()
+---+---------+--------+
| ID|FirstName|LastName|
+---+---------+--------+
|  1|    Navee|Srikanth|
|  3|   Naveen|        |
+---+---------+--------+

df.where("FirstName != ''").show()
+---+---------+--------+
| ID|FirstName|LastName|
+---+---------+--------+
|  1|    Navee|Srikanth|
|  3|   Naveen|        |
+---+---------+--------+

答案 1 :(得分:3)

您应该按以下方式进行操作

join_Df1.filter(join_Df1.FirstName.isNotNull()).show

希望这有帮助!

答案 2 :(得分:0)

我认为您可能需要的是notnull()

因此,这是您在csv文件my_test.csv中的输入:

ID,FirstName,LastName
1,Navee,Srikanth

2,,Srikanth

3,Naveen

代码:

import pandas as pd
df = pd.read_csv("my_test.csv")

print(df[df['FirstName'].notnull()])

输出:

  ID FirstName  LastName
0   1     Navee  Srikanth
2   3    Naveen       NaN

这就是你想要的! df[df['FirstName'].notnull()]

df['FirstName'].notnull()的输出:

0     True
1    False
2     True

这会创建一个数据框df,其中df['FirstName'].notnull()返回True

如何检查? df['FirstName'].notnull()如果FirstName列的值不为空,则返回True,如果存在NaN,则返回False