Python 遍历 DataFrame 某一列并转为字符串:详细教程
要遍历 DataFrame 的某一列并将每一行转换为字符串,可以使用 iterrows() 方法来遍历 DataFrame 的每一行,并使用 str() 函数将每个元素转换为字符串。
下面是一个示例代码:
import pandas as pd
# 创建一个示例 DataFrame
data = {'Name': ['John', 'Mike', 'Sarah'],
'Age': [25, 30, 35]}
df = pd.DataFrame(data)
# 遍历 Name 列的每一行并转换为字符串
for index, row in df.iterrows():
name_str = str(row['Name'])
print(name_str)
输出结果为:
John
Mike
Sarah
在上面的代码中,我们首先创建了一个示例 DataFrame。然后,使用 iterrows() 方法遍历了 DataFrame 的每一行。在循环中,使用 str() 函数将每个 Name 列的元素转换为字符串,并打印出来。
原文地址: https://www.cveoy.top/t/topic/fqZq 著作权归作者所有。请勿转载和采集!