【发布时间】:2022-08-10 02:05:01
【问题描述】:
我遇到了这个问题,我有一个如下所示的数据框(最后 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 列中的值创建一个新数据框。我想根据最后 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() 对于将值放入列表很有用。我唯一的想法是如果我需要分别循环遍历每一列并将其附加到正确的行,但我不知道该怎么做。
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