Python附加到数据帧中的特定列

2024-10-02 22:34:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含3列的数据帧df和一个根据循环的列名从文本文件创建字符串的循环:

exampletext = "Nr1 thisword1 and Nr2 thisword2 and Nr3 thisword3"
Columnnames = ("Nr1", "Nr2", "Nr3")
df1= pd.DataFrame(columns = Columnnames)
for i in range(0,len(Columnnames)):
   solution = exampletext.find(Columnnames[i])
   lsolution= len(Columnnames[i])
   Solutionwords = exampletext[solution+lsolution:solution+lsolution+10]

现在我想把solutionwords追加到dataframe df1末尾的正确字段中,例如,当查找Nr1时,我想将solutionwords追加到名为Nr1的列中。 我尝试使用append并创建一个列表,但是这只会在列表的末尾追加。我需要数据帧来根据我要找的单词来分隔单词。谢谢你的帮助!在

编辑所需的输出和可读性: 期望的输出应该是一个数据帧,如下所示:

1 | 2 | 3尼泊尔卢比

这个字1 |这个字2 |这个字3


Tags: and数据列表len单词df1solution末尾
1条回答
网友
1楼 · 发布于 2024-10-02 22:34:50

我假设单元格值的单词总是跟在列名后面,并用空格隔开。在这种情况下,我可能会尝试通过将值添加到字典中,然后在字典包含所需数据之后从中创建一个数据帧来实现这一点,例如:

example_text = "Nr1 thisword1 and Nr2 thisword2 and Nr3 thisword3"
column_names = ("Nr1", "Nr2", "Nr3")

d = dict()
split_text = example_text.split(' ')
for i, text in enumerate(split_text):
    if text in column_names:
        d[text] = split_text[i+1]

df = pd.DataFrame(d, index=[0])

这会给你:

^{pr2}$

相关问题 更多 >