可以使用apply()函数来将DataFrame中的列表转换为字符串,并使用strip()函数去掉字符串两端的括号'[]'。

以下是一个示例代码:

import pandas as pd

# 创建一个包含列表的DataFrame
df = pd.DataFrame({'col1': [[1, 2, 3], [4, 5, 6], [7, 8, 9]]})

# 定义一个函数,将列表转换为字符串并去掉括号
def list_to_string(lst):
    return str(lst).strip('[]')

# 使用apply函数将列表转换为字符串
df['col1'] = df['col1'].apply(list_to_string)

print(df)

输出结果为:

  col1
0  1, 2, 3
1  4, 5, 6
2  7, 8, 9

在这个示例中,apply()函数将list_to_string函数应用于col1列的每个元素,将每个列表转换为字符串并去掉括号。最后输出的DataFrame中的col1列包含了转换后的字符串。

Pandas DataFrame 列表转字符串并去除括号

原文地址: https://www.cveoy.top/t/topic/qx0G 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录