[英]Pandas Indexing and Column Creation
I have a dataset, df
. 我有一个数据集df
。
I extracted another dataset from df
, df_rec
, based on a certain condition. 我根据特定条件从df
提取了另一个数据集df_rec
。
I can access the indexes of df_rec
by df_rec.index.
我可以通过df_rec.index.
访问df_rec
的索引df_rec.index.
Now, I want to create a column in df, where the index in df if matches with indexes in df_rec should be populated as 1 otherwise 0. 现在,我想在df中创建一列,如果与df_rec中的索引匹配,则df中的索引应填充为1,否则填充为0。
Any help, will be appreciated. 任何帮助将不胜感激。
I am thinking, like, which throws error. 我在想,这会引发错误。
df['reccurences'] = 0
df['reccurences'][df.index in df_rec.index] = 1
You can use map
on the index of df
to chek whether it is in df_res
and set the value accordingly as shown below. 您可以使用df
索引上的map
来检查它是否在df_res
并相应地设置值,如下所示。
df = pd.DataFrame()
df['X'] = [1, 2, 3, 4, 5, 6]
df['Y'] = [10, 20, 30, 40, 50, 60]
df_res = df.loc[df['X'] > 3]
df['C'] = df.index.map(lambda x : 1 if x in df_res.index else 0)
OR you can do like this 或者你可以这样做
df['C'] = [1 if x in df_res.index else 0 for x in df.index]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.