How Do I Add a String Value to Dataframe?
string = 'cool'
df = pd.DataFrame(columns=['string_values'])

Append

df.append(string)

I get this error when I try to append it into df. (Is it only for numerical data?)

cannot concatenate object of type "<class 'str'>"; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid

I just want to add a string value string = 'cool' into the dataframe, but I get this error.

2 Answers

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)
3

If you need to add more than a single value, see @jezraels answer. 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

Check the docs.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest