MultiIndex Pandas DataFrame 到 Spark DataFrame 和缺失索引
MultiIndex Pandas DataFrame to Spark DataFrame & Missing Indexes
拥有一个 MultiIndex Pandas DataFrame,如何在不丢失索引的情况下将其转换为 Spark DataFrame。这可以使用玩具示例轻松测试:
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(8, 4), index=arrays)
df_spark = sqlContext.createDataFrame(df)
缺少所有索引。为了保留索引,我还需要注意其他事项吗?
Spark SQL没有索引的概念,所以如果要保留它,必须先重置或赋值给一个列:
df_spark = sqlContext.createDataFrame(df.reset_index(drop=False))
这将为索引中的每个字段创建一个 DataFrame
和一个附加列:
df_spark.printSchema()
root
|-- level_0: string (nullable = true)
|-- level_1: string (nullable = true)
|-- 0: double (nullable = true)
|-- 1: double (nullable = true)
|-- 2: double (nullable = true)
|-- 3: double (nullable = true)
您还可以使用 inplace
来避免额外的内存开销:
df.reset_index(drop=False, inplace=True)
df_spark = sqlContext.createDataFrame(df)
拥有一个 MultiIndex Pandas DataFrame,如何在不丢失索引的情况下将其转换为 Spark DataFrame。这可以使用玩具示例轻松测试:
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(8, 4), index=arrays)
df_spark = sqlContext.createDataFrame(df)
缺少所有索引。为了保留索引,我还需要注意其他事项吗?
Spark SQL没有索引的概念,所以如果要保留它,必须先重置或赋值给一个列:
df_spark = sqlContext.createDataFrame(df.reset_index(drop=False))
这将为索引中的每个字段创建一个 DataFrame
和一个附加列:
df_spark.printSchema()
root
|-- level_0: string (nullable = true)
|-- level_1: string (nullable = true)
|-- 0: double (nullable = true)
|-- 1: double (nullable = true)
|-- 2: double (nullable = true)
|-- 3: double (nullable = true)
您还可以使用 inplace
来避免额外的内存开销:
df.reset_index(drop=False, inplace=True)
df_spark = sqlContext.createDataFrame(df)