python - Python:将列表转换为数据框中的列
问题描述
我有一个数据框,其中一列具有如下值列表。
ID Source
1 [apple,mango]
2 [grapes]
现在我试图消除我的数据框中的值列表并创建一个新的数据框,如下所示:
ID Source
1 apple
1 mango
2 grapes
我正在尝试使用以下代码实现上述目标:
duplicates = pd.DataFrame()
for _, row in file_df.iterrows(): # file_df is the original dataframe with list of values
leng = len(row.Source_sentences)
for j in row.Source_sentences:
itr = [row.ID,j]
df2 = pd.DataFrame(row.ID, j, columns=["ID","Source"])
print(itr)
duplicates.append(df2,ignore_index=True)
idx = idx +1
print(duplicates)
我收到以下错误
TypeError: Index(...) must be called with a collection of some kind, 'Apple.' wa
s passed
有人可以指出我的代码哪里出错了
解决方案
你可以这样尝试:
输入:
df = {'ID': [1, 2],'Source': [["apple","mango"], ["grapes"]]}
df = pd.DataFrame(data=df)
ID Source
0 1 [apple, mango]
1 2 [grapes]
df1 = (df['Source'].apply(lambda x: pd.Series(x))
.stack()
.reset_index(level=1, drop=True)
.to_frame('Source')
.join(df[['ID']], how='left')
)
输出:
Source ID
0 apple 1
0 mango 1
1 grapes 2
推荐阅读
- jquery - 添加功能以在单击时从当前项目中删除类
- database - 如果服务器的 IP 更改并安装在此服务器 oracle 数据库上会有什么影响?
- azure - Azure CosmosDB 如何将 CreateItem 费用降至 5 RU?
- javascript - 是否可以获取触发了哪个自定义函数的元素 ID?
- html - 使用悬停伪元素不起作用
- python-3.x - Matplotlib:如何获得彼此重叠而不是并排的颜色条?
- node.js - node js和mongodb无法连接docker-compose
- javascript - 错误:元素类型无效:应为字符串(用于内置组件)或类/函数..检查渲染方法
- python - 如何在 AirTest IDE 的 HTML 报告中获取失败状态?
- c# - SQL Server 2017 上的 CLR Strict Security - 程序集已签名,但突然再次出现“clr strict security”异常