我想从数据框中的一列中获取匹配项。属性列是一个列表。下面是一个示例:
date tableNameFrom tableNameJoin attributeName
1 29-03-2019 film language [film.languageId, language.languageID, film.filmID]
2 30-03-2019 inventory as i rental as r [i.inventoryId, r.filmId]
这是我尝试过的:
df1 = (pd.DataFrame(df['attribute'].values.tolist())
.stack()
.str.split('.', expand=True)
.reset_index(drop=True))
df1.columns = ['tableName','attributeName']
print(df1)
还有我得到的输出:
tableName attributeName
1 film languageId
2 language languageID
3 film filmId
需要的输出:
date tableName attributeName
1 29-03-2019 film languageId
2 29-03-2019 language languageID
3 29-03-2019 film filmId
4 30-03-2019 inventory inventoryId
5 30-03-2019 rental filmId
任何想法我该怎么办?感谢您的帮助。
答案 0 :(得分:1)
首先由Series.str.split
和as
为字典创建字典:
df3 = df[['tableNameFrom','tableNameJoin']].stack().str.split(' as ', expand=True).dropna()
d = dict(zip(df3[1], df3[0]))
print (d)
{'i': 'inventory', 'r': 'rental'}
将索引参数添加到DataFrame
构造函数中,并删除最后一个reset_index
:
df1 = (pd.DataFrame(df['attributeName'].values.tolist(), index=df.index)
.stack()
.str.split('.', expand=True))
df1.columns = ['tableName','attributeName']
print(df1)
tableName attributeName
1 0 film languageId
1 language languageID
2 film filmID
2 0 i inventoryId
1 r filmId
仅选择列date
和DataFrame.join
新的DataFrame
:
df2 = df[['date']].join(df1.reset_index(level=1, drop=True))
最后Series.replace
,按字典:
df2['tableName'] = df2['tableName'].replace(d)
df2 = df2.reset_index(drop=True)
print (df2)
date tableName attributeName
0 29-03-2019 film languageId
1 29-03-2019 language languageID
2 29-03-2019 film filmID
3 30-03-2019 inventory inventoryId
4 30-03-2019 rental filmId