pandas 如何向 DataFrame 添加字符串值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53236855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:08:44  来源:igfitidea点击:

How do I add a string value to DataFrame?

pythonpandas

提问by Chipmunkafy

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

当我尝试将其附加到 df 时出现此错误。(是否仅适用于数值数据?)

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.

我只想string = 'cool'在数据框中添加一个字符串值,但出现此错误。

回答by jezrael

I think best is use DataFramecontructor and assign one element list:

我认为最好是使用DataFrame构造函数并分配一个元素列表:

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)

回答by Edgar Ramírez Mondragón

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:

如果您需要添加多个值,请参阅@jezraels 答案。如果您只需要添加一个值,您可以这样做:

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.

检查文档