Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a dataframe from a list using loops

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
like image 887
Sam Avatar asked Sep 19 '26 15:09

Sam


1 Answers

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.

like image 167
jpp Avatar answered Sep 22 '26 04:09

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!