可以使用Python中的pandas库来按照字符串拆分和格式化特定列对数据框进行变换。下面是一个示例代码:
import pandas as pd
# 创建一个示例数据框
data = {'Name': ['John Smith', 'Jane Doe', 'Mary Johnson'],
'Age': [30, 25, 35],
'Location': ['New York', 'London', 'Paris']}
df = pd.DataFrame(data)
# 按照空格拆分Name列,并将拆分后的姓和名分别放入新的两列中
df[['First Name', 'Last Name']] = df['Name'].str.split(' ', expand=True)
# 格式化Age列中的数据为带有单位的字符串
df['Formatted Age'] = df['Age'].astype(str) + ' years old'
# 打印变换后的数据框
print(df)
输出结果如下:
Name Age Location First Name Last Name Formatted Age
0 John Smith 30 New York John Smith 30 years old
1 Jane Doe 25 London Jane Doe 25 years old
2 Mary Johnson 35 Paris Mary Johnson 35 years old
在以上示例中,首先使用str.split()
方法将Name列按照空格进行拆分,并使用expand=True
参数将拆分后的结果放入新的两列中。然后,使用astype()
方法将Age列转换为字符串,并通过字符串拼接的方式添加单位。最后,将拆分后的列和格式化后的列添加到原始数据框中。
上一篇:按照子对象中参数的值排序