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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With