您可以使用:#remove ‘, split by +, create Series
s1 = df.Products.str.strip(“‘”)
.str.split(‘+’, expand=True)
.stack()
.reset_index(drop=True, level=1)
remove ‘, split by +, create Series, strip spaces
s2 = df.Orders.str.strip(“‘”)
.str.split(‘+’, expand=True)
.stack().str.strip()
.reset_index(drop=True, level=1)
if need add ‘
s1 = “‘” + s1 + “‘”
s2 = “‘” + s2 + “‘”
df1 = pd.DataFrame({‘Products’:s1, ‘Orders’:s2}, index=s1.index)
print (df1)
Orders Products
0 ‘ord1’ ‘A’
0 ‘ord2’ ‘G’
1 ‘ord3’ ‘C’
2 ‘ord4’ ‘H’
2 ‘ord5’ ‘Z’
3 ‘ord6’ ‘K’
4 ‘ord7’ ‘T’
5 ‘ord#’ ‘K’
6 ‘ord8’ ‘R’
6 ‘ord9’ ‘D’
6 ‘ord10’ ‘S’
7 ‘ord11’ ‘A’
^{pr2}$
按注释编辑:
使用^{}创建df1:…
…
df1 = pd.concat([s1, s2], keys=(‘Orders’, ‘Products’), axis=1)
print (df1)
Orders Products
0 ‘A’ ‘ord1’
0 ‘G’ ‘ord2’
1 ‘C’ ‘ord3’
2 ‘H’ ‘ord4’
2 ‘Z’ ‘ord5’
3 ‘K’ ‘ord6’
4 ‘T’ ‘ord7’
5 ‘K’ ‘ord#’
6 ‘R’ ‘ord8’
6 ‘D’ ‘ord9’
6 ‘S’ ‘ord10’
7 ‘A’ ‘ord11’
print(df.drop([‘Orders’, ‘Products’], axis=1)
.join(df1)
.dropna(subset=[‘Cust-id’])
.reset_index(drop=True))
Cust-id Sex Country Orders Products
0 ‘Cu1’ ‘F’ ‘FR’ ‘A’ ‘ord1’
1 ‘Cu1’ ‘F’ ‘FR’ ‘G’ ‘ord2’
2 ‘Cu2’ ‘M’ ‘US’ ‘C’ ‘ord3’
3 ‘Cu3’ ‘M’ ‘UK’ ‘H’ ‘ord4’
4 ‘Cu3’ ‘M’ ‘UK’ ‘Z’ ‘ord5’
5 ‘Cu4’ ‘F’ ‘RU’ ‘K’ ‘ord6’
6 ‘Cu5’ ‘M’ ‘US’ ‘T’ ‘ord7’
7 ‘Cu6’ ‘F’ ‘US’ ‘R’ ‘ord8’
8 ‘Cu6’ ‘F’ ‘US’ ‘D’ ‘ord9’
9 ‘Cu6’ ‘F’ ‘US’ ‘S’ ‘ord10’
10 ‘Cu7’ ‘M’ ‘UK’ ‘A’ ‘ord11’
Original: https://blog.csdn.net/weixin_36180912/article/details/112906149
Author: 少轻侯
Title: python创建两列n行的表格_Python Pandas:基于两列在dataFrame中创建新行
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/755169/
转载文章受原作者版权保护。转载请注明原作者出处!