Python追加到数据框中的特定列

时间:2018-11-14 13:59:02

标签: python python-3.x dataframe append

我有一个包含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]

现在我想在正确的字段中在数据帧df1的末尾附加解决方案字词,例如当寻找Nr1时,我想将solutionword附加到名为Nr1的列上。 我尝试使用追加并创建列表,但这只会追加在列表的末尾。我需要数据框以根据需要的单词来分隔单词。谢谢您的帮助!

编辑所需的输出和可读性: 所需的输出应为数据框,如下所示:

Nr1 | Nr2 | Nr3

thisword1 | thisword2 | thisword3

1 个答案:

答案 0 :(得分:1)

我假设您输入的单元格值一词始终跟随您的列名,并用空格分隔。在这种情况下,我可能会尝试通过将您的值添加到字典中,然后在包含所需数据之后从中创建数据框来实现此目的,例如:

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])

这将为您提供:

>>> df 
         Nr1        Nr2        Nr3
0  thisword1  thisword2  thisword3
相关问题