如何将单个系列具体化为字符串 Python Pandas 库?

使用熊猫。我们可以将单个系列转换为字符串。让我们举一些例子,看看它是如何工作的。Series.to_string()

示例

使用字符串 dtype 数据创建一个熊猫系列,然后将其转换为字符串。

# 创建一个系列
ds = pd.Series(["a", "b", "c", "a"], dtype="string")
print(ds) # 展示系列
s = ds.to_string() # 转换为字符串
print()
print(repr(s)) display converted output

解释

变量 ds 通过将 dtype 定义为字符串来保存包含所有字符串数据的 Pandas 系列。然后使用pandas.Series.to_string方法将系列转换成字符串,这里我们定义为. 最后,将转换后的字符串分配给 s 变量。并通过使用函数返回可打印的表示字符串来显示输出(变量 s)。ds.to_string()repr()

输出结果

0   a
1   b
2   c
3   a
dtype: string

'0   a\n1   b\n2   c\n3   a'

上述块的第一部分表示一个 dtype 为字符串的系列的输出,该块的第二部分表示单个 Pandas 系列的转换后的字符串输出。

在上面的示例中,我们将字符串 dtype 系列转换为字符串,但我们可以将系列转换为任何 dtype。让我们再举一个例子。

示例

ds = pd.Series([1,2,3,3])
print(ds)
s = ds.to_string()
print()
print(repr(s))

解释

在这个例子中,它在 pandas 系列中只有整数类型的数据。为此,直接向该方法声明一个整数列表,它将创建一个熊猫系列。之后,使用方法将“ds”系列转换为字符串。pd.Series()ds.to_string()

输出结果

0   1
1   2
2   3
3   3
dtype: int64

'0   1\n1   2\n2   3\n3   3'

我们可以在上面的块中看到来自具有 int64 dtype 数据的单个系列的转换后的字符串。像这样,我们可以使用 pandas to_string 方法将单个系列具体化为一个字符串。