g.pickardou
g.pickardou

Reputation: 35853

How can I refer a column by its index?

I can use col("mycolumnname") function to get the column object. Based on the documentation the only possible parameter is the name of the column.

Is there any way to get the column object by its index?

Upvotes: 0

Views: 891

Answers (2)

Joshua
Joshua

Reputation: 561

Try this:

Let n be the index variable (integer).

df.select(df.columns[n]).show()

Upvotes: 2

过过招
过过招

Reputation: 4199

Is the expected result like this?

import pyspark.sql.functions as F
...
data = [
    (1, 'AC Milan'),
    (2, 'Real Madrid'),
    (3, 'Bayern Munich')
]
df = spark.createDataFrame(data, ['id', 'club'])
df.select(F.col('club')).show()
df.select(df['club']).show()

Upvotes: 1

Related Questions