2024-09-27 20:15:27 发布
网友
目前,我有50个来自同一路径('\home\data')的数据集,每个数据集示例如下:
dataset1.csv
数据集2.csv
数据集3.csv
我想首先组合所有句子,然后按id分组并使它们成为一个数据集如下所示:
如果有人能给我一些建议,我将不胜感激
您可以使用glob读取所有文件,并在转换后使用pandas.concat连接这些文件:
glob
pandas.concat
from glob import glob df = pd.concat([(pd.read_csv(filename) .groupby('id', as_index=False) .agg({'sentence': '\n'.join, 'platform': 'first', 'id': 'first'}) ) for filename in glob('dataset*.csv') ])
通过首先将数据帧连接在一起,然后使用groupby将句子连接在一起(按平台和id分组),可以获得所需的输出
groupby
import pandas as pd df1 = pd.DataFrame({'sentence': ['hello, I am good.', 'hello, how are u.', 'hello, xxxxxxxx.'], 'platform': ['CNN', 'CNN', 'CNN'], 'id': ['001', '001', '001']}) df2 = pd.DataFrame({'sentence': ['ok, xxxxxxxx.', 'ok, xxxxxxxx.', 'ok, xxxxxxxxxx.'], 'platform': ['FOX', 'FOX', 'FOX'], 'id': ['002', '002', '002']}) df3 = pd.DataFrame({'sentence': ['well, xxxxxxxx.', 'well, xxxxxxxx.', 'well, xxxxxxxxxx.'], 'platform': ['MMM', 'MMM', 'MMM'], 'id': ['003', '003', '003']}) df4 = pd.concat([df1, df2, df3]) df5 = df4.groupby(['platform', 'id'])['sentence'].apply('\n'.join).reset_index() # reorder and rename the columns df5 = df5[['sentence', 'platform', 'id']] df5.columns = ['content', 'platform', 'id'] print(df5)
输出:
content platform id 0 hello, I am good.\nhello, how are u.\nhello, x... CNN 001 1 ok, xxxxxxxx.\nok, xxxxxxxx.\nok, xxxxxxxxxx. FOX 002 2 well, xxxxxxxx.\nwell, xxxxxxxx.\nwell, xxxxxx... MMM 003
您还可以颠倒顺序,在每个单独的数据帧上使用groupby,然后将结果连接在一起
您可以使用
glob
读取所有文件,并在转换后使用pandas.concat
连接这些文件:通过首先将数据帧连接在一起,然后使用
groupby
将句子连接在一起(按平台和id分组),可以获得所需的输出输出:
您还可以颠倒顺序,在每个单独的数据帧上使用
groupby
,然后将结果连接在一起相关问题 更多 >
编程相关推荐