Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a string value to DataFrame?

Tags:

python

pandas

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.

like image 903
Chipmunkafy Avatar asked Nov 10 '18 07:11

Chipmunkafy


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)
like image 126
jezrael Avatar answered Oct 07 '22 07:10

jezrael


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.

like image 40
Edgar Ramírez Mondragón Avatar answered Oct 07 '22 07:10

Edgar Ramírez Mondragón