【发布时间】:2015-11-21 17:06:27
【问题描述】:
我正在处理主题建模数据,其中我有一个数据框,其中包含一小部分主题以及每个文档或作者的分数(称为“分数”),另一个数据框包含所有 250 个单词的前三个单词主题(称为“单词”)。
我正在尝试将两个数据框组合在一起,以便在“分数”中增加一列,其中“单词”中的前三个单词出现在“分数”中包含的每个主题中。这对于将数据可视化为热图很有用,因为seaborn 或pyplot 将自动从此类数据框中获取标签。
我尝试了各种各样的合并和连接命令,但没有得到想要的结果。奇怪的是:根据我对相关文档和那里的示例的理解,似乎最合乎逻辑的命令(即在两个df上使用axis=1和join="inner"),适用于玩具数据但确实不适用于我的真实数据。
这是我的玩具数据以及我用来生成它并进行合并的代码:
import pandas as pd
## Defining the two data frames
scores = pd.DataFrame({'author1': ['1.00', '1.50'],
'author2': ['2.75', '1.20'],
'author3': ['0.55', '1.25'],
'author4': ['0.95', '1.3']},
index=[1, 3])
words = pd.DataFrame({'words': ['cadavre','fenêtre','musique','mariage']},
index=[0, 1, 2, 3])
## Inspecting the two dataframes
print("\n==scores==\n", scores)
print("\n==words==\n", words)
## Merging the dataframes
merged = pd.concat([scores, words], axis=1, join="inner")
## Check the result
print("\n==merged==\n", merged)
正如预期的那样,这是输出:
==scores==
author1 author2 author3 author4
1 1.00 2.75 0.55 0.95
3 1.50 1.20 1.25 1.3
==words==
words
0 cadavre
1 fenêtre
2 musique
3 mariage
==merged==
author1 author2 author3 author4 words
1 1.00 2.75 0.55 0.95 fenêtre
3 1.50 1.20 1.25 1.3 mariage
这正是我想用我的真实数据完成的。虽然这两个数据框看起来与测试数据没有什么不同,但合并的结果是一个空的数据框。
这是我真实数据中的一个小例子:
someScores(完整表格):
blanche policier
108 0.003028 0.017494
71 0.002997 0.016956
115 0.029324 0.016127
187 0.004867 0.017631
122 0.002948 0.015118
firstWords(仅前 5 行;索引为 249,“someScores”中的所有索引条目在“firstwords”中都有对应项):
topicwords
0 château-pays-intendant (0)
1 esclave-palais-race (1)
2 linge-voisin-chose (2)
3 question-messieurs-réponse (3)
4 prince-princesse-monseigneur (4)
5 arbre-branche-feuille (5)
我的合并命令:
dataToPlot = pd.concat([someScores, firstWords], axis=1, join="inner")
以及生成的数据框(空)!
Empty DataFrame
Columns: [blanche, policier, topicwords]
Index: []
我尝试了许多变体,例如使用 merge 代替,或者创建额外的列来复制索引,然后合并具有 left_on 和 right_on 的那些,但是我要么得到相同的结果,要么只得到 NaN “主题词”列。
任何提示和帮助将不胜感激!
【问题讨论】:
-
您的索引中没有匹配的值,因此连接的 df 为空,索引对
someScores是否重要? -
数据框
firstWords有250行,索引从0到249(这里只显示0-5),所以应该有一个匹配的值。someScores中的索引很重要,因为这些是特定主题。此外,它们的顺序很重要(它们按行间标准差的递减排序,并应按此顺序出现在热图中。) -
索引的 dtype 是什么?看起来一个可能是int或str?您能否显示两个 dfs 的
type(df.index)的输出,这可以解释为什么它们不匹配 -
是的,它们看起来是不同的数据类型:
dtype firstWords: <class 'pandas.core.index.Int64Index'>和dtype someScores: <class 'pandas.core.index.Index'>。我该怎么办? -
你可以尝试投
someScores.index = someScores.index.astype(np.int64)然后加入
标签: python pandas merge concat