gpt4 book ai didi

python - pandas DataFrame 不合并但不报错

转载 作者:行者123 更新时间:2023-12-05 03:41:20 24 4
gpt4 key购买 nike

我有一个简单的循环,将句子编号和数字 + 1 相加,并将其创建到一个具有命名列 onetwo 的 DataFrame 中。我试图将每次迭代的结果合并到主 DataFrame df 中,但它似乎没有合并它,也没有抛出错误。

这是可重现的代码:

df = pd.DataFrame()
for i in range(1, 6):
sentence = pd.DataFrame((f'This is sentence {i}', i+1)).transpose()
sentence.columns = ['one', 'two']
print(sentence)
if df.empty:
df = sentence
print('creating')
else:
df = df.merge(sentence, how='left', on=['one', 'two'])
print('merging')

但是 df 的最终结果看起来只有一行:

                  one two
0 This is sentence 1 2

有人可以向我解释为什么这没有合并吗?

谢谢

编辑

最终结果应该是这样的:

                  one two
0 This is sentence 1 2
1 This is sentence 2 3
2 This is sentence 3 4
3 This is sentence 4 5
4 This is sentence 5 6

与合并时索引均为0有关吗?

最佳答案

for i in range(1, 6):
sentence = pd.DataFrame([(f'This is sentence {i}', i+1)], columns=['one', 'two'])
df = df.merge(sentence, how='outer')```
>>> df
one two
0 This is sentence 1 2
1 This is sentence 2 3
2 This is sentence 3 4
3 This is sentence 4 5
4 This is sentence 5 6

关于python - pandas DataFrame 不合并但不报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67821101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com