Python 如何通过标记现有数据帧的内容来创建新的数据帧?
我对python/pandas非常陌生,需要社区的帮助。这就是我要做的 我读过一个json文件,其中包含以下数据:Python 如何通过标记现有数据帧的内容来创建新的数据帧?,python,pandas,dataframe,Python,Pandas,Dataframe,我对python/pandas非常陌生,需要社区的帮助。这就是我要做的 我读过一个json文件,其中包含以下数据: (文章的)内容 ID(唯一标识符) 标题(文章标题) 使用此代码: import pandas as pd df = pd.read_json(path_to_file, lines=True) 所需输出:我想创建一个新的数据帧,使其具有两列 ID(唯一标识符) 句子(在df的内容栏中拆分句子) 到目前为止我所能做的: 找出标记器来自nltk,以及如何将其传递给apply函数
import pandas as pd
df = pd.read_json(path_to_file, lines=True)
所需输出:我想创建一个新的数据帧,使其具有两列
result = df["content"].apply(sent_tokenize)
我的问题是如何获得上述所需格式的结果。您可以将
apply
的返回值指定为df中的一个新列
df[“句子”]=df[“内容”]。应用(已发送\u标记化)
如果要删除其他列(标题和内容),也可以通过分配来完成:
df=df[[“ID”,“句子”]]
使用itertuples迭代数据帧
import pandas as pd
df = pd.DataFrame([['hi how are you. i am fine. hope this help you','ABC']], columns = ['sent','ID'])
df
sent ID
0 hi how are you. i am fine. hope this help you ABC
new_sent =[]
for row in df.itertuples():
for sent in sent_tokenize(row[1]):
new_sent.append((sent, row[2]))
#creating dataframe for new_sent
df_new = pd.DataFrame(new_sent, columns = ['tokenized_sent', 'ID'])
#o/p
tokenized_sent ID
0 hi how are you. ABC
1 i am fine. ABC
2 hope this help you ABC
解释
for row in df.itertuples():
print(row)
#o/p
Pandas(Index=0, sent='hi how are you. i am fine. hope this help you', ID='ABC')
print(row[0])
0
print(row[1])
'hi how are you. i am fine. hope this help you'
print(row[2])
'ABC'
现在,我们正在对第二个元素执行标记化,并在新的列表中添加带有它id的句子
new_list = []
for sent in sent_tokenize(row[1]):
new_list.append((sent, row[2]))
print((sent, row[2]))
o/p
('hi how are you.', 'ABC')
('i am fine.', 'ABC')
('hope this help you', 'ABC')
# now create dataframe with this new_sent
df_new = pd.DataFrame(new_sent, columns = ['tokenized_sent', 'ID'])
也许我不能清楚地表达我的观点。我需要apply的结果来跨越多行,例如Row1=1,第一句话。行2=1,第二句,行3=1,第三句。其中数字1表示算术ID@ImranAli哦,好的,很抱歉我没有正确理解。谢谢你的帮助,你能给代码特别是嵌套for循环添加一些解释吗,
dfu new
如何选择正确的ID
@Imran Ali,添加了解释。。。希望这项工作为你