【问题标题】:Python Pandas - Split Column with multiple names in first name and last name columnPython Pandas - 在名字和姓氏列中有多个名称的拆分列
【发布时间】:2022-01-11 15:59:06
【问题描述】:

我有一个 csv 文件,其列如下:

并希望将其转换为这种格式:

不幸的是,到目前为止,我还没有找到一个好方法来做到这一点。 Python 和 Pandas 是否可以像这样拆分列?

【问题讨论】:

    标签: python pandas csv


    【解决方案1】:

    你甚至不需要熊猫。这是一个代码。由于您未提供数据,因此未进行测试。

    对于未来,如果您提供您尝试编写的任何代码以及可以帮助您更轻松的数据,那就太棒了。

    names = []
    with open("filename.csv", 'r') as f:
        for line in f.readlines():
            split_names = line.split(' ')
            names.append(split_names[0], ' '.join(split_names[1:]))
    

    PS:代码假定文件中没有标题。因此,您必须删除标题或跳过代码中的行。

    【讨论】:

    • 还有str.partition 避免加入:first_name, _, last_name = line.partition(" ")。 pandas 的 str 访问器也实现了这一点。
    • 谢谢,我以后会记住的
    • @Neither 哦,这很整洁!我不知道。使用str.partition,这可以是一条线。
    猜你喜欢
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2015-03-08
    相关资源
    最近更新 更多