Pandas 从列中拆分值并生成序列号
我在df中有两列。每列在一行中有多个值。我想在另一个表中拆分新行中的每个值并生成序号。给定的数据是Pandas 从列中拆分值并生成序列号,pandas,postgresql,Pandas,Postgresql,我在df中有两列。每列在一行中有多个值。我想在另一个表中拆分新行中的每个值并生成序号。给定的数据是 xy 76.25, 345.65 87.12,96.45 78.12,35.1,98.27 85.23,65.2,56.63 新的df应该是这样的 x76.25 y 87.12 序列号1 x 345.65 y 96.45 序列号2 x78.12 y 85.23 序列号1 x 35.1 y 65.21
xy
76.25, 345.65 87.12,96.45
78.12,35.1,98.27 85.23,65.2,56.63
新的df应该是这样的
x76.25
y 87.12
序列号1
x 345.65
y 96.45
序列号2
x78.12
y 85.23
序列号1
x 35.1
y 65.21
序列号2
x 98.27
y 56.63
序列号3
所有值都是字符串。我不知道该怎么做。我应该写一个函数还是数据帧中有任何命令?非常感谢您的帮助您可以使用
iterrows()
+concat()
:
希望这有帮助。您可以使用
iterrows()
+concat()
:
希望这有帮助。@user19您可以使用它将数据帧转换为
记录
,并将它们写入任何数据库
。您还可以将数据写入csv
,并使用cli工具插入。网上有很多例子。祝你好运;)@用户19只需问一个新问题。在db中添加表结构、数据帧和预期结果。我相信您会得到快速的解释。@user19您可以使用它将数据帧转换为记录
,并将它们写入任何db
。您还可以将数据写入csv
,并使用cli工具插入。网上有很多例子。祝你好运;)@用户19只需问一个新问题。在db中添加表结构、数据帧和预期结果。我相信你会很快得到解释的答案。
df = pd.DataFrame({
'x': ('76.25,345.65', '78.12,35.1,98.27'),
'y': ('87.12,96.45', '85.23,65.2,56.63')
})
def get_parts():
for index, row in df.iterrows():
x = row['x'].split(',')
y = row['y'].split(',')
for index, _ in enumerate(x):
# len(x) must be equal len(y)...
yield 'x', x[index]
yield 'y', y[index]
# generate number after each splitted item
yield 'sequence number', index + 1
# generate Series from parts and union into new dataframe
new_df = pd.concat([
pd.Series([p[1]], [p[0]])
for p in get_parts()
])