import pandas as pd
df = pd.DataFrame(dict(
city=['Seattle'],
hood=[['SoDo', 'Maple Leaf', 'View Ridge', 'North Gate', 'SLU']],
))
print('df before exploding:\n', df)
df = df.explode('hood')
print('\ndf after exploding:\n', df)
输出:
df before exploding:
city hood
0 Seattle [SoDo, Maple Leaf, View Ridge, North Gate, SLU]
df after exploding:
city hood
0 Seattle SoDo
0 Seattle Maple Leaf
0 Seattle View Ridge
0 Seattle North Gate
0 Seattle SLU
Process finished with exit code 0
编辑:OP回复:
yes it is exactly what i want but i have just a problem m box is like that : df before exploding: hood =[' SoDo, Maple Leaf, View Ridge, North Gate, SLU '] so i tried with explod but it is not possible because the , is a string charachter
如果是这种情况,并且它只是一个字符串,则执行以下额外步骤:
import pandas as pd
df = pd.DataFrame(dict(
city=['Seattle'],
hood=[['SoDo, Maple Leaf, View Ridge, North Gate, SLU']],
))
print('df before exploding:\n', df)
df['hood'] = df['hood'].apply(lambda x: x[0].split(', '))
print('\ndf after splitting string in list:\n',df)
df = df.explode('hood')
print('\ndf after exploding:\n', df)
输出:
df before exploding:
city hood
0 Seattle [SoDo, Maple Leaf, View Ridge, North Gate, SLU]
df after splitting string in list:
city hood
0 Seattle [SoDo, Maple Leaf, View Ridge, North Gate, SLU]
df after exploding:
city hood
0 Seattle SoDo
0 Seattle Maple Leaf
0 Seattle View Ridge
0 Seattle North Gate
0 Seattle SLU
Process finished with exit code 0
您应该用一个预期输入和输出的示例来充实这个问题,但我认为您需要使用pandas.DataFrame.explode实现类似的功能
输出:
编辑:OP回复:
如果是这种情况,并且它只是一个字符串,则执行以下额外步骤:
输出:
相关问题 更多 >
编程相关推荐