我遇到了这个问题,我有一个数据帧,看起来像下面(最后3列中的值通常是4-5个字母数字代码).
import pandas as pd
data = {'ID':['P39','S32'],
'Name':['Pipe','Screw'],
'Col3':['Test1, Test2, Test3','Test6, Test7'],
'Col4':['','Test8, Test9'],
'Col5':['Test4, Test5','Test10, Test11, Test12, Test13']
}
df = pd.DataFrame(data)
ID | Name | Col3 | Col4 | Col5 | |
---|---|---|---|---|---|
0 | P39 | Pipe | Test1, Test2, Test3 | Test4, Test5 | |
1 | S32 | Screw | Test6, Test7 | Test8, Test9 | Test10, Test11, Test12, Test13 |
我想扩展这个数据帧,或者基于每行最后3列中的值创建一个新的数据帧.我想根据最后三行中以逗号分隔的最大值创建更多行.然后,我希望在所有展开的行中保持前2列相同.但是我想用原始列中的一个值填充扩展行中的最后3列.
在上面的示例中,第一行表示我总共需要3行(Col3在3个值时最多),第二行表示我总共需要4行(Col5在4个值时最多).所需输出应符合以下要求:
ID | Name | Col3 | Col4 | Col5 | |
---|---|---|---|---|---|
0 | P39 | Pipe | Test1 | Test4 | |
1 | P39 | Pipe | Test2 | Test5 | |
2 | P39 | Pipe | Test3 | ||
3 | S32 | Screw | Test6 | Test8 | Test10 |
4 | S32 | Screw | Test7 | Test9 | Test11 |
5 | S32 | Screw | Test12 | ||
6 | S32 | Screw | Test13 |
我首先找到了一种计算所需行数的方法.我还想把这些值附加到同一个循环中的新数据帧中.尽管如此,我不知道如何将最后3列中的值分开,并将它们逐个追加到行中.我知道str.split()对于将值放入列表非常有用.我唯一的 idea 是,如果我需要分别遍历每一列并将其附加到正确的行中,但我不知道如何做到这一点.
output1 = pd.DataFrame(
columns = ['ID', 'Name', 'Col3', 'Col4', 'Col5'])
for index, row in df.iterrows():
output2 = pd.DataFrame(
columns = ['ID', 'Name', 'Col3', 'Col4', 'Col5'])
col3counter = df.iloc[index, 2].count(',')
col4counter = df.iloc[index, 3].count(',')
col5counter = df.iloc[index, 4].count(',')
numofnewcols = max(col3counter, col4counter, col5counter) + 1
iter1 = df.iloc[index, 2].split(', ')
iter2 = df.iloc[index, 3].split(', ')
iter3 = df.iloc[index, 4].split(', ')
#for q in iter1
#output2.iloc[ , 2] =
output1 = pd.concat([output1, output2], ignore_index=True)
del output2