我有一个文本文件:
每次都可以更改,行数也可以更改,每行包含以下内容:
string (can contain one word, two or even more) ^ string of one word
EX:
level country ^ layla
hello sandra ^ organization
hello people ^ layla
hello samar ^ organization
我想使用熊猫创建数据帧,以便:
item0 ( country, people)
item1 (sandra , samar)
因为例如,每次有layla时,我们都返回属于它的最正确的名称,并将其添加为上面显示的第二列,在本例中是(country,people),我们将layla称为item0,并作为数据帧的索引。我似乎无法安排这一点,我不知道如何做的逻辑返回任何重复的“^”后,并返回其所属的最正确的名称列表。到目前为止,我的试验没有真正做到这一点:
def text_file(file):
list=[]
file_of_text = "text.txt"
with open(file_of_context) as f:
for l in f:
l_dict = l.split(" ")
list.append(l_dict)
return(list)
def items(file_of_text):
list_of_items= text_file(file_of_text)
for a in list_of_items:
for b in a:
if a[-1]==
def main():
file_of_text = "text.txt"
if __name__ == "__main__":
main()
从指定“^”作为分隔符并使用任意列名开始
然后我们分开得到我们想要的值。我相信这在熊猫16中是新发现的
然后我们将B列分组并应用tuple函数。注意:我们正在重置索引,以便稍后使用
使用字符串“item”和索引创建新列
假设您的文件名为
file_of_text.txt
,包含以下内容:您可以使用以下代码行将数据从文件中获取到与所需输出类似的数据帧:
其思想是从文本文件中读取行,然后使用
split
方法从re
模块中拆分每一行。然后将结果传递给DataFrame
方法以生成名为data
的数据帧,该数据帧用于创建所需的数据帧final_data
。结果应如下所示:如果你有任何问题,请看一下剧本并进一步提问。你知道吗
我希望这有帮助。你知道吗
相关问题 更多 >
编程相关推荐