简体   繁体   中英

How to create a new column in a Pandas series based off of conditions derived from another series

I have 3 Pandas Series:

Master
0 LA
1 NY
2 HOU

Source
0 LA
1 NY

Target
0 NY
1 HOU

I want to create a dataframe out of Master with new columns based off whether or not a city is found as a source/target. The result would be something like this:

Master    Source   Target
0 LA        True    False
1 NY        True    True
2 HOU       False   True

You can create a DataFrame this way, using df.isin to check if a value is in a given array/Series

# Question data
master = pd.Series(['LA', 'NY', 'HOU'])
source = pd.Series(['LA', 'NY'])
target = pd.Series(['NY', 'HOU'])

df = pd.DataFrame()

df['Master'] = master
df['Source'] = df.Master.isin(source)
df['Target'] = df.Master.isin(target)

df
    Master  Source  Target
0   LA      True    False
1   NY      True    True
2   HOU     False   True

Try this:

Master = pd.Series({
    0: 'LA',
    1: 'NY',
    2: 'HOU'
})
Source = pd.Series({
    0: 'LA',
    1: 'NY',
})
Target = pd.Series({
    0: 'NY',
    1: 'HOU',
})
 
df = Master.to_frame()
df['Source'] = df[0].isin(Source)
df['Target'] = df[0].isin(Target)
print(df)

     0  Source  Target
0   LA    True   False
1   NY    True    True
2  HOU   False    True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM