重命名列并创建新的dataframe

2024-09-28 05:24:35 发布

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

我对此表示怀疑,因为我更改了两个数据帧中的名称列

df1.rename(columns={'polarity':'polarityBiden','Sentiment_Type':'TextblobBiden','compound':'compoundBiden','sentiment_type':'VaderBiden','score':'scoreBayenBiden'})

我得到了输出:

polarityBiden   subjectivity    TextblobBiden   compoundBiden   VaderBiden  scoreBayenBiden
0   0.000000    0.047619    NEUTRAL -0.3818 NEGATIVE    Negative

第二,它是相同的,但当我想要concat两个df和代码时

result = pd.concat([df1, df2], axis=1, join="inner")
result

一切都回到了上一页。版本

polarity    subjectivity    Sentiment_Type  compound    sentiment_type  score   polarity    subjectivity    Sentiment_Type  compound    sentiment_type  score
0   0.000000    0.047619    NEUTRAL -0.3818 NEGATIVE    Negative    0.160000    0.466667    POSITIVE    -0.6705 NEGATIVE

如何使用新名称列链接两个df


Tags: 名称typescoredf1sentimentnegativecompoundpolarity
2条回答

^{}函数创建数据帧的副本,而不是基于原始数据帧进行重命名。您必须将其重新分配给原始名称,或者使用inplace=True参数强制其在原始数据帧而不是副本上工作

您可以按以下方式执行(重新分配):

df1 = df1.rename(columns={'polarity':'polarityBiden','Sentiment_Type':'TextblobBiden','compound':'compoundBiden','sentiment_type':'VaderBiden','score':'scoreBayenBiden'})

或者使用inplace=True

df1.rename(columns={'polarity':'polarityBiden','Sentiment_Type':'TextblobBiden','compound':'compoundBiden','sentiment_type':'VaderBiden','score':'scoreBayenBiden'}, inplace=True)

只需在concat之前重命名df2

df2.columns = df1.columns

您还可以将两个数据帧与来自numpy的vstack连接起来,并将生成的ndarray转换为数据帧:

result = pd.DataFrame(np.vstack([df1, df2]), columns=df1.columns)

numpy.vstack()函数用于垂直堆叠输入数组序列以形成单个数组

相关问题 更多 >

    热门问题