[英]Error in pyspark.pandas when trying to reindex columns
I have a dataframe that is missing certain values and I want to generate records for those and input the value with 0.我有一个 dataframe 缺少某些值,我想为这些值生成记录并输入值为 0。
My df looks like this:我的 df 看起来像这样:
import pyspark.pandas as ps
import databricks.koalas as ks
import pandas as pd
data = {'Region': ['Africa','Africa','Africa','Africa','Africa','Africa','Africa','Asia','Asia','Asia'],
'Country': ['South Africa','South Africa','South Africa','South Africa','South Africa','South Africa','South Africa','Japan','Japan','Japan'],
'Product': ['ABC','ABC','ABC','XYZ','XYZ','XYZ','XYZ','DEF','DEF','DEF'],
'Year': [2016, 2018, 2019,2016, 2017, 2018, 2019,2016, 2017, 2019],
'Price': [500, 0,450,750,0,0,890,19,120,3],
'Quantity': [1200,0,330,500,190,70,120,300,50,80],
'Value': [600000,0,148500,350000,0,29100,106800,74300,5500,20750]}
df = ps.DataFrame(data)
Some entries in this df are missing, such as the year 2017
for South Africa
and the year 2018
for Japan
.此 df 中的某些条目缺失,例如
South Africa
的2017
年和Japan
的2018
。
I want to generate those entries and add 0
in the columns Quantity
, Price
and Value
.我想生成这些条目并在
Quantity
、 Price
和Value
列中添加0
。
I managed to do this on a smaller dataset using pandas
, however, when I try to implement this using pyspark.pandas
, I get an error.我设法使用
pandas
在较小的数据集上执行此操作,但是,当我尝试使用pyspark.pandas
实现此操作时,出现错误。
This is the code I have so far:这是我到目前为止的代码:
(df.set_index(['Region', 'Country','Product','Year'])
.reindex(ps.MultiIndex.from_product([df['Region'].unique(),
df['Country'].unique(),
df['Product'].unique(),
df['Year'].unique()],
names=['Region', 'Country','Product','Year']),
fill_value=0)
.reset_index())
Whenever I run it, I get the following issue:每当我运行它时,我都会遇到以下问题:
PandasNotImplementedError: The method `pd.Series.__iter__()` is not implemented. If you want to collect your data as an NumPy array, use 'to_numpy()' instead.
Any ideas why this might happen and how to fix it?任何想法为什么会发生这种情况以及如何解决它?
Ok so looking closer at the synatx for ps.MultiIndex, the variables have to be passed as list, so I had to add .tolist()
after each column's unique values.好的,仔细查看 ps.MultiIndex 的 synatx,变量必须作为列表传递,所以我必须在每列的唯一值之后添加
.tolist()
。 Code below:下面的代码:
(df.set_index(['Region', 'Country','Product','Year'])
.reindex(ps.MultiIndex.from_product([df['Region'].unique().tolist(),
df['Country'].unique().tolist(),
df['Product'].unique().tolist(),
df['Year'].unique().tolist()],
names=['Region', 'Country','Product','Year']),
fill_value=0)
.reset_index())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.