python - 如何将一列的值与数据框中的另一列匹配

标签 python python-3.x pandas postgresql dataframe

我想从数据框中的一列与其他列中获取匹配项。下面是一个例子:

  tableNameFrom   tableNameJoin   attributeName
1 film            language        [film.languageId, language.languageID]
2 inventory       rental          [invetory.inventoryId, rental.filmId]

在上面的例子中,我想用 attributeName 在 tablenameFrom 和 tablenameJoin 之间进行匹配。这里需要输出:

  tableName    attributeName
1 film         languageId
2 language     languageID
3 inventory    inventoryId
4 rental       filmId

最佳答案

我的解决方案只适用于 attributeName 列,因为从样本数据中可以得到所有需要输出的数据。

使用Series.str.split首先通过 ,,然后通过 DataFrame.stack reshape DataFrame并按拆分。:

df1 = (df['attributeName'].str.split(', ', expand=True)
                          .stack()
                          .str.split('.', expand=True)
                          .reset_index(drop=True))
df1.columns = ['tableName','attributeName']
print (df1)
  tableName attributeName
0      film    languageId
1  language    languageID
2  invetory   inventoryId
3    rental        filmId

编辑:

如果值是列表,使用 DataFrame 构造函数:

print (type(df.loc[1, 'attributeName']))
<class 'list'>

df1 = (pd.DataFrame(df['attributeName'].values.tolist())
                          .stack()
                          .str.split('.', expand=True)
                          .reset_index(drop=True))
df1.columns = ['tableName','attributeName']
print (df1)
  tableName attributeName
0      film    languageId
1  language    languageID
2  invetory   inventoryId
3    rental        filmId

关于python - 如何将一列的值与数据框中的另一列匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55772841/

相关文章:

python - 在 Python 中为 True 定义值时的奇怪行为

python - mysql-python 连接器同时适用于 python2.7 和 3.4

python - 如何/在哪里定义/传递cloudformation参数?

python - Pandas .apply() : How to use a formula in apply() that involves values from preceding cells in the same column?

python 语法错误: invalid syntax %matplotlib inline

Python __name__() 主函数

python - 嵌套字典理解以避免空值

Python/OpenCV —细菌簇中的质心确定

python - Fuzzywuzzy 在 Python 中匹配来自不同数据帧的多列

python - 如何将带有依赖项的 python 脚本打包成 zip/tar?