如何将多个python数据帧组合成一个数据帧?

2024-09-21 07:44:52 发布

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

我有超过1500个python数据帧需要组合成一个大的数据帧。我遇到的问题是,数据帧具有唯一的列标题和不同的大小。你知道吗

例如,数据帧1是:

type    sc98*c.firstname    sc98*c.lastname    sc98*c.username    text                  createdAt    statusofExpiration
need    John                Doe                johndoe            I need a new car.     111111       expired

数据帧2是:

type    l8!7s4fn.firstname    l8!7s4fn.lastname    l8!7s4fn.username    text                    tags.0    tags.1    image.0        createdAt    statusOfExpiration
need    Matt                  Smith                mattsmith            I need a yoga trainer.  yoga      trainer   blankurl.com/  22222        fulfilled

我想得到一个数据帧,比如:

type    firstname    lastname    username    text                    createdAt    statusofExpiration    tags.0    tags.1    image.0
need    John         Doe         johndoe     I need a new car.       111111       expired       
need    Matt         Smith       mattsmith   I need a yoga trainer.  222222       fulfilled             yoga      trainer   blankurl.com/

如前所述,由于dataframes的大小可变,我无法按索引调用值,也无法按列名调用值,因为dataframes具有唯一标识符(例如。id.用户名)在列标题中。你知道吗

有什么办法可以解决这个问题吗?你知道吗


Tags: 数据text标题typeusernamefirstnameneedjohn
2条回答

由于数据帧具有唯一的列标题和不同的大小,因此连接数据帧的方法并不简单。我建议调查以下内容:

df.filter(like='firstname')  # select columns containing the word firstname

通过这种方式,可以循环遍历所有数据帧中的列名,并基于部分匹配对它们进行重命名。你知道吗

看看这个帖子:Pandas rename colums with wildcard

您可以这样做来连接或合并多个数据帧。希望这对你有帮助!你知道吗

df1 = DataFrame(
{
    'First Name': firstname_list,
    'Last Name': lastname_list,
 }
)

df2 = DataFrame(
{
    'Key1': value_list1,
    'Key2': value_list2,
 }
)

frames = [df1, df2]

concatenated_df = pd.concat(frames)
concatenated_df.to_csv(r'dataset.csv', sep=',', index=False)

相关问题 更多 >

    热门问题