如何在 python(类似 groupby())- pandas 库中创建其他数据框作为图例的列
how to create column with other dataframe as legend in python (groupby() alike)- pandas library
我想使用 df2 作为我的主要 df 的图例 ('main_df')
“代码”需要什么?
main_df = pd.DataFrame({'genre_NAME': ['comedy', 'action', 'horror'], 'genre_id': [nan, nan, nan]})
df2 = pd.DataFrame({'genre': ['comedy', 'horror'], 'id': [0, 1]})
#main_df is not relate to df2
some code
#result
print(main_df)
*OUTPUT =* 'genre_NAME': ['comedy', 'action', 'horror'], 'genre_id': [0, nan,1]
您可以使用 df.loc[]
访问和更改数据框中的特定值。所以在你的情况下:
for _, line in df2.iterrows():
main_df.loc[main_df.genre_NAME == line.genre, "genre_id"] = line.id
我想使用 df2 作为我的主要 df 的图例 ('main_df')
“代码”需要什么?
main_df = pd.DataFrame({'genre_NAME': ['comedy', 'action', 'horror'], 'genre_id': [nan, nan, nan]})
df2 = pd.DataFrame({'genre': ['comedy', 'horror'], 'id': [0, 1]})
#main_df is not relate to df2
some code
#result
print(main_df)
*OUTPUT =* 'genre_NAME': ['comedy', 'action', 'horror'], 'genre_id': [0, nan,1]
您可以使用 df.loc[]
访问和更改数据框中的特定值。所以在你的情况下:
for _, line in df2.iterrows():
main_df.loc[main_df.genre_NAME == line.genre, "genre_id"] = line.id