0

New to Python. Would like to convert below list to pandas dataframe with fixed number of columns

[['Teja'], ['22', 'Male'], ['Viha'], ['Female'], ['Male'], ['Vinay'], ['32', 'Female'], ['Sowmya']]

DataFrame-Output

3
  • IS your list organized as [[name],[age,gender]] or as your example? Commented Dec 6, 2020 at 18:21
  • No. it is not organized as [[name],[age,gender]]. It is just a random list Commented Dec 6, 2020 at 18:22
  • What have you tried so far? Please include your code attempts Commented Dec 6, 2020 at 19:08

2 Answers 2

1

Hope this is what you are looking at.

import pandas as pd

a = [
    ["Teja"],
    ["22", "Male"],
    ["Viha"],
    ["Female"],
    ["Male"],
    ["Vinay"],
    ["32", "Female"],
    ["Sowmya"],
]

name = []
age = []
gender = []
for item in a:
    if "Male" in item or "Female" in item:
        if item[0].isnumeric():
            age.append(item[0])
            gender.append(item[1])
        else:
            age.append("None")
            gender.append(item[0])
        continue
    name.append(item[0])

data = {"name": name, "age": age, "gender": gender}

print(name, age, gender)

df = pd.DataFrame(data)

print(df)
Sign up to request clarification or add additional context in comments.

Comments

0

Create a dictionary like this:

d = {
    'name'  : ['Teja', 'Viha', 'Vinay', 'Sowmya'],
    'age'   : [22, None, None, 32],
    'gender': ['Male', 'Female', 'Male', 'Female']
}
my_dataframe = pandas.DataFrame(d)
print(my_dataframe)

The output would be like:

     name   age  gender
0    Teja  22.0    Male
1    Viha   NaN  Female
2   Vinay   NaN    Male
3  Sowmya  32.0  Female

1 Comment

The question was how to convert existing data, not how to type it and make dataframe

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.