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