2

I am trying to get a column data type from a dataframe

Here is a sample code:

    print training_data.schema
    print 'fields'
    print training_data.schema.fields
    print 'names'
    print training_data.schema.names

The above code prints as shown below: StructType(List(StructField(id,LongType,true),StructField(text,StringType,true),StructField(label,DoubleType,true))) fields [StructField(id,LongType,true), StructField(text,StringType,true), StructField(label,DoubleType,true)] names ['id', 'text', 'label']

But how can I get the datatype for label column ? Thanks a lot for your time.

Regards

1

3 Answers 3

1
df['col label'].dtype

Is one option.

Edit

name_dtype = df['col label'].dtype.name
Sign up to request clarification or add additional context in comments.

6 Comments

I tried this, but it prints: Column<label['dtype']>
tried, it prints <bound method Column.alias of Column<label['dtype']>>
Oops, I think we might be talking about different dataframes. My answer was with regards to Pandas dataframes and not SQL dataframes. My bad. If you have Pandas installed, you could always convert your SQL dataframe to a Pandas dataframe and try my solution.
oh,ok I will try that. Sorry I am new to this python. What is the difference between SQL dataframe and pandas dataframe?
How do I get the data type in SQL dataframe?
|
1

Here is copy-paste example of how to get column names and colum types for pandas dataframe:

import pandas as pd

list = [['Tom',34, 45.5], ['Jack',23, 60.5]]
df = pd.DataFrame(list, columns=["Name","Age","Pay"])

for column in df.columns:
    print("Column ", column, "is dtype:", df[column].dtype.name)

result:

Column  Name is dtype: object
Column  Age is dtype: int64
Column  Pay is dtype: float64

Comments

0

Thanks for all the responses. I found the below solution, hoping it will be helpful to any one looking for the answer:

       for f, v in zip(df.schema.fields, df.schema.names):
          if v == colname:
            datatype = f.dataType

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.