Python:如何拆分数据框中的字符串列?

标签 python python-3.x pandas

我有一个包含两列的数据框,一列是 Date,另一列是 Location(Object) 数据类型,下面是带有值的 Location 列的格式:

 Date                                            Location
1     07/12/1912                            AtlantiCity, New Jersey   
2     08/06/1913                 Victoria, British Columbia, Canada   
3     09/09/1913                                 Over the North Sea   
4     10/17/1913                         Near Johannisthal, Germany   
5     03/05/1915                                    Tienen, Belgium   
6     09/03/1915                              Off Cuxhaven, Germany   
7     07/28/1916                              Near Jambol, Bulgeria   
8     09/24/1916                                Billericay, England   
9     10/01/1916                               Potters Bar, England   
10    11/21/1916                                     Mainz, Germany

我的要求是用 "," 分隔符拆分 Location 并只保留它的第二部分 (例如新泽西、加拿大、德国、英国等。) 在位置列中。我还必须检查它是否只有一个元素(单个元素没有“,”的值)

有没有一种方法可以使用预定义的方法来完成,而无需循环每一行?

如果这个问题不符合标准,我很抱歉,因为我是 Python 的新手并且还在学习。

最佳答案

一种直接的方法是对列的每个元素应用 split 方法并选择最后一个元素:

df.Location.apply(lambda x: x.split(",")[-1])

1             New Jersey
2                 Canada
3     Over the North Sea
4                Germany
5                Belgium
6                Germany
7               Bulgeria
8                England
9                England
10               Germany
Name: Location, dtype: object

要检查每个单元格是否只有一个元素,我们可以在列上使用 str.contains 方法:

df.Location.str.contains(",")

1      True
2      True
3     False
4      True
5      True
6      True
7      True
8      True
9      True
10     True
Name: Location, dtype: bool

关于Python:如何拆分数据框中的字符串列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38676968/

相关文章:

python - 在 Spyder IDE 中释放 matplotlib 内存

Python zip 函数 - 奇怪的结果

python - 如果 range() 是 Python 3.3 中的生成器,为什么我不能在范围上调用 next()?

python - 在 Python 函数中使用输入语句作为参数

python - 将一个数组中的唯一值映射到另一个数组的相应总和

python - 基于 pandas 数据框中通配符的字典查找

python - Python 2.6 中的 Maketrans

python - 在Python或Shell中逐行比较字段数据

python - 对列表内的值进行分组

python - 对多列应用 lambda 函数