Python/pyspark 数据框重新排列列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42912156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python/pyspark data frame rearrange columns
提问by User12345
I have a data frame in python/pyspark with columns id
time
city
zip
and so on......
我在 python/pyspark 中有一个带有列id
time
city
zip
等的数据框......
Now I added a new column name
to this data frame.
现在我name
向这个数据框中添加了一个新列。
Now I have to arrange the columns in such a way that the name
column comes after id
现在,我必须安排这样的列的name
列来后id
I have done like below
我做了如下
change_cols = ['id', 'name']
cols = ([col for col in change_cols if col in df]
+ [col for col in df if col not in change_cols])
df = df[cols]
I am getting this error
我收到此错误
pyspark.sql.utils.AnalysisException: u"Reference 'id' is ambiguous, could be: id#609, id#1224.;"
Why is this error occuring. How can I rectify this.
为什么会出现这个错误。我该如何纠正这一点。
回答by Alex
You can use select
to change the order of the columns:
您可以使用select
来更改列的顺序:
df.select("id","name","time","city")
回答by melchtheitroad55
If you're working with a large number of columns:
如果您正在处理大量列:
df.select(sorted(df.columns))