Spark 데이터 프레임이 비어 있는지 확인하는 방법
지금 은 비어 df.count > 0
있는지 확인하는 데 사용해야 합니다 DataFrame
. 그러나 그것은 비효율적입니다. 더 좋은 방법이 있습니까?
감사.
추신 : 비어 DataFrame
있지 않은 경우 에만 저장하도록 비어 있는지 확인하고 싶습니다.
Spark 2.1.0의 경우 내 제안은 head(n: Int)
또는 take(n: Int)
함께 사용 isEmpty
하는 것입니다.
df.head(1).isEmpty
df.take(1).isEmpty
이에 상응하는 Python 사용 :
len(df.head(1)) == 0 # or bool(df.head(1))
len(df.take(1)) == 0 # or bool(df.take(1))
df.first()
및 df.head()
을 사용 java.util.NoSuchElementException
하면 DataFrame이 비어 있는 경우 를 모두 반환합니다 . first()
호출 head()
호출하는 직접 head(1).head
.
def first(): T = head()
def head(): T = head(1).head
head(1)
Array를 반환하므로 head
해당 Array를 사용하면 java.util.NoSuchElementException
DataFrame이 비어있을 때 발생합니다 .
def head(n: Int): Array[T] = withAction("head", limit(n).queryExecution)(collectFromPlan)
따라서을 호출하는 대신 직접 head()
사용 head(1)
하여 배열을 가져온 다음 isEmpty
.
take(n)
또한 head(n)
...
def take(n: Int): Array[T] = head(n)
그리고 limit(1).collect()
동일하다 head(1)
(통지 limit(n).queryExecution
에서 head(n: Int)
다음 모두 동일하므로 적어도 내가 말할 수있는 것과, 방법), 당신은 잡을 필요가 없습니다 java.util.NoSuchElementException
DataFrame가 비어있을 때 예외를.
df.head(1).isEmpty
df.take(1).isEmpty
df.limit(1).collect().isEmpty
나는 이것이 오래된 질문이라는 것을 알고 있으므로 새로운 버전의 Spark를 사용하는 사람에게 도움이되기를 바랍니다.
나는 단지 기본 RDD
. Scala에서 :
df.rdd.isEmpty
파이썬에서 :
df.rdd.isEmpty()
즉,이 모든 작업은 call take(1).length
이므로 Rohan이 대답 한 것과 동일한 작업을 수행 할 것입니다.
당신의 장점이 걸릴 수 있습니다 head()
(또는 first()
(가) 있는지 확인하기 위해) 기능을 DataFrame
하나의 행이 있습니다. 그렇다면 비어 있지 않습니다.
당신이 df.count > 0
. 모든 실행기에서 모든 파티션의 수를 가져 와서 Driver에서 합산합니다. 수백만 개의 행을 처리 할 때 시간이 걸립니다.
이를 수행하는 가장 좋은 방법 df.take(1)
은 null인지 확인 하고 수행하는 것 입니다. 이것은 java.util.NoSuchElementException
시도를 두는 것이 더 나아질 것 df.take(1)
입니다.
데이터 프레임 take(1)
은 빈 행 대신 완료 되면 오류를 반환합니다 . 오류가 발생하는 특정 코드 줄을 강조 표시했습니다.
Java 사용자의 경우 데이터 세트에서 이것을 사용할 수 있습니다.
public boolean isDatasetEmpty(Dataset<Row> ds) {
boolean isEmpty;
try {
isEmpty = ((Row[]) ds.head(1)).length == 0;
} catch (Exception e) {
return true;
}
return isEmpty;
}
가능한 모든 시나리오를 확인합니다 (empty, null).
Spark 2.4.0부터 Dataset.isEmpty
.
그것의 구현 입니다 :
def isEmpty: Boolean =
withAction("isEmpty", limit(1).groupBy().count().queryExecution) { plan =>
plan.executeCollect().head.getLong(0) == 0
}
Note that a DataFrame
is no longer a class in Scala, it's just a type alias (probably changed with Spark 2.0):
type DataFrame = Dataset[Row]
In Scala you can use implicits to add the methods isEmpty()
and nonEmpty()
to the DataFrame API, which will make the code a bit nicer to read.
object DataFrameExtensions {
implicit def extendedDataFrame(dataFrame: DataFrame): ExtendedDataFrame =
new ExtendedDataFrame(dataFrame: DataFrame)
class ExtendedDataFrame(dataFrame: DataFrame) {
def isEmpty(): Boolean = {
Try{dataFrame.first.length != 0} match {
case Success(_) => false
case Failure(_) => true
}
}
def nonEmpty(): Boolean = !isEmpty
}
}
Here, other methods can be added as well. To use the implicit conversion, use import DataFrameExtensions._
in the file you want to use the extended functionality. Afterwards, the methods can be used directly as so:
val df: DataFrame = ...
if (df.isEmpty) {
// Do something
}
If you are using Pypsark, you could also do:
len(df.head(1)) > 0
df1.take(1).length>0
The take
method returns the array of rows, so if the array size is equal to zero, there are no records in df
.
I found that on some cases:
>>>print(type(df))
<class 'pyspark.sql.dataframe.DataFrame'>
>>>df.take(1).isEmpty
'list' object has no attribute 'isEmpty'
this is same for "length" or replace take() by head()
[Solution] for the issue we can use.
>>>df.limit(2).count() > 1
False
PySpark에, 당신은이를 사용할 수 있습니다 bool(df.head(1))
얻을 수 True
의 False
값을
False
데이터 프레임에 행이 없으면 반환 됩니다.
다음과 같이 할 수 있습니다.
val df = sqlContext.emptyDataFrame
if( df.eq(sqlContext.emptyDataFrame) )
println("empty df ")
else
println("normal df")
참고 URL : https://stackoverflow.com/questions/32707620/how-to-check-if-spark-dataframe-is-empty
'Programing' 카테고리의 다른 글
정방향 클래스 개체에서 속성을 찾을 수 없습니다. (0) | 2020.10.21 |
---|---|
포트 3000에서 수신 대기하는 프로세스를 종료하는 쉘 스크립트? (0) | 2020.10.21 |
힙 메모리 (malloc / new)를 사용하면 비 결정적 프로그램이 생성됩니까? (0) | 2020.10.21 |
Android TextView 텍스트가 래핑되지 않음 (0) | 2020.10.21 |
Imagemagick : 고정 너비, 비례 높이로 변환 (0) | 2020.10.21 |