3

I have a list containing strings, and I am planning to create a dataframe by using loops. May be the below example will help in better understanding:

s=["first","second","third"]
a=s[0]
for i in range(1,len(s)):
    print(i)
    print(s[i])
    a=a+s[i]
#########
print(a)
'first;second;third'
## Creating dataframe####
d=pd.DataFrame()
d["c"]=1
d["text"]=a

This gives me a empty dataframe.

Output expected as :

c       text

1       first;second;third

2 Answers 2

2

You can use dict with enumerate for this:

s = ["first", "second", "third"]

df = pd.DataFrame.from_dict(dict(enumerate(s, 1)), orient='index')\
                 .reset_index()\
                 .rename(columns={'index': 'c', 0: 'text'})

#    c    text
# 0  1   first
# 1  2  second
# 2  3   third

Avoiding "building a dataframe in a loop". Your best option is almost always to build a list or a dictionary, then feed into pd.DataFrame.

The above example works for any length s.

Sign up to request clarification or add additional context in comments.

Comments

0

Are you looking for?

import pandas as pd
s=["first","second","third"]
a = "; ".join(s)

d=pd.DataFrame([{"text": a, "c": 1}])
print(d)

Output:

   c                  text
0  1  first; second; third

2 Comments

I am not sure about the length of the list, so I have a used a loop there. Also I need a identifier, in above case it is denoted with d["c"]. This identifier will be also looped in. With this requirement can I get a dataframe? in my case why I am getting a empty dataframe?
@Sam if the identifier is an index you can use the enumerate() function when performing a dictionary comprehension.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.