如何在数据框中分隔两行

2024-04-26 06:39:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张多伦多社区的表格,有些情况下,当你把两个或三个社区放在同一个盒子里,所以同一行(对于同一个行政区)我想把它们分成两行,怎么做请! 我在用熊猫。 多谢各位


Tags: 情况社区表格盒子行政区
1条回答
网友
1楼 · 发布于 2024-04-26 06:39:20

您应该用一个预期输入和输出的示例来充实这个问题,但我认为您需要使用pandas.DataFrame.explode实现类似的功能

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

相关问题 更多 >