close

How do I add a string value to DataFrame?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I add a string value to DataFrame in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do I add a string value to DataFrame?

  1. How do I add a string value to DataFrame?

    If strings are generated in loop best is append them to one list and then pass to constructor only once:

  2. I add a string value to DataFrame

    If strings are generated in loop best is append them to one list and then pass to constructor only once:

Method 1

I think best is use DataFrame contructor and assign one element list:

string = 'cool'
df = pd.DataFrame([string], columns=['string_values'])
print (df)
  string_values
0          cool

If strings are generated in loop best is append them to one list and then pass to constructor only once:

L  = []
for x in range(3):
    L.append(string)

df = pd.DataFrame(L, columns=['string_values'])
print (df)
  string_values
0          cool
1          cool
2          cool

Performance:

In [43]: %%timeit
    ...: L  = []
    ...: for x in range(1000):
    ...:     value1 = "dog" + str(x)
    ...:     L.append(value1)
    ...: 
    ...: df = pd.DataFrame(L, columns=['string_values'])
    ...: 
1.29 ms ± 56.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [44]: %%timeit
    ...: df = pd.DataFrame(columns=['string_values'])
    ...: for x in range(1000):
    ...:     value1 = "dog" + str(x)
    ...:     df = df.append({'string_values': value1}, ignore_index=True)
    ...: 
1.19 s ± 34.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Method 2

If you need to add more than a single value, If you only need to add a single value, you can do this:

import pandas as pd

df = pd.DataFrame(columns=['string_values'])
value1 = "dog"
df = df.append({'string_values': value1}, ignore_index=True)

#   string_values
# 0           dog

value2 = "cat"
df = df.append({'string_values': value2}, ignore_index=True)

#   string_values
# 0           dog
# 1           cat

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read