Pandas 如何将Pandas DataFrame字符串列拆分为两列
在本文中,我们将介绍如何使用Pandas在DataFrame中将一个字符串列拆分为两个列。有时在数据处理中,我们会遇到这种情况,需要将一个单独的字符串列划分成两个或多个列。
阅读更多:Pandas 教程
DataFrame的示例
我们使用以下DataFrame来演示如何将字符串列拆分为两列:
import pandas as pd
data = {
'Name': ['Tom', 'Kate', 'Oliver', 'Jack'],
'Age': [25, 28, 22, 32],
'Location': ['New York,USA', 'London,UK', 'Paris,France', 'Beijing,China']
}
df = pd.DataFrame(data)
print(df)
这将创建如下DataFrame:
Name Age Location
0 Tom 25 New York,USA
1 Kate 28 London,UK
2 Oliver 22 Paris,France
3 Jack 32 Beijing,China
我们可以看到,Location
列包含两个信息:城市和国家/地区。现在我们将展示如何将Location
列拆分为两个列:City
和Country/Region
。
使用str.split()方法拆分列
Pandas DataFrame有一个方便的方法str.split()
,用于拆分字符串列。它需要一个拆分器,并且可以选择分割成几列(默认为-1,即所有列)。
我们可以使用以下代码将Location
列拆分为两列:City
和Country/Region
。
new = df['Location'].str.split(",", n=1, expand=True)
df['City'] = new[0]
df['Country/Region'] = new[1]
df.drop(columns=['Location'], inplace=True)
print(df)
这将输出:
Name Age City Country/Region
0 Tom 25 New York USA
1 Kate 28 London UK
2 Oliver 22 Paris France
3 Jack 32 Beijing China
str.split()
方法将Location
列拆分为两个列,即City
和Country/Region
,并将其附加到DataFrame上。我们还丢弃了原始的Location
列,因为我们已经用它所拆分出的新列完全代替了。
在这个例子中,","
是拆分器,并且在n
参数中指定了要拆分的最大数量。在本例中,我们只需要拆分出两列,将n=1
传递给str.split()
方法即可。拆分后,我们将结果存储在一个名为new的新DataFrame对象中,并且使用它的第0列和第1列分别创建了新的City
和Country/Region
列。
总结
在本文中,我们学习了如何使用Pandas DataFrame的str.split()
方法将字符串列拆分为两列。这种技术在许多数据处理场景中都非常有用,例如需要使用地址列或名字列的Last,First格式的情况。在实际工作中,我们可以根据需要选择拆分器数量和拆分的列数。