的方法如下:
import pandas as pd
data = {'row1': ['A|B|C', 'D|E|F', 'G|H|I'],
'row2': ['1|2|3', '4|5|6', '7|8|9']}
df = pd.DataFrame(data)
apply
函数和split
方法将每行按照分隔符进行拆分:df['row1'] = df['row1'].apply(lambda x: x.split('|'))
df['row2'] = df['row2'].apply(lambda x: x.split('|'))
df.rename(index={0: 'new_row1', 1: 'new_row2', 2: 'new_row3'}, inplace=True)
完整的代码如下:
import pandas as pd
data = {'row1': ['A|B|C', 'D|E|F', 'G|H|I'],
'row2': ['1|2|3', '4|5|6', '7|8|9']}
df = pd.DataFrame(data)
df['row1'] = df['row1'].apply(lambda x: x.split('|'))
df['row2'] = df['row2'].apply(lambda x: x.split('|'))
df.rename(index={0: 'new_row1', 1: 'new_row2', 2: 'new_row3'}, inplace=True)
这样,DataFrame的每一行都被按照分隔符拆分成了一个列表,并且另一行的索引也被重命名为了'new_row1'、'new_row2'和'new_row3'。
领取专属 10元无门槛券
手把手带您无忧上云