2 columns dataframe as the first screenshot. I want to add new columns (by the contents in the Note column from the original dataframe) to tell if the Note column contains the new column’s header text.
Example as the second screenshot.
Some lines work for a few columns. When there are a lot of new columns, it’s not efficient.
What would be the good way to do so? Thank you.
import pandas as pd
from io import StringIO
csvfile = StringIO(
'''Name\tNote
Mike\tBright, Kind
Lily\tFriendly
Kate\tConsiderate, energetic
John\tReliable, friendly
Ale\tBright''')
df = pd.read_csv(csvfile, sep = '\t', engine='python')
col_list = df['Note'].tolist()
n_list = []
for c in col_list:
for _ in c.split(','):
n_list.append(_)
df = df.assign(**dict.fromkeys(n_list, ''))
df["Bright"][df['Note'].str.contains("Bright")] = "Yes"
You can try .str.get_dummies
then replace 1
with Yes
df = df.join(df['Note'].str.get_dummies(', ').replace({1: 'Yes', 0: ''}))
print(df)
Name Note Bright Considerate Friendly Kind Reliable energetic friendly
0 Mike Bright, Kind Yes Yes
1 Lily Friendly Yes
2 Kate Considerate, energetic Yes Yes
3 John Reliable, friendly Yes Yes
4 Ale Bright Yes
You may also like…
- Why fluentd loss most of it's log while using http output plugin (in similar timestamp)
- Java Mouse Listener – Can event type be detected inside of an event?
- flutter build ipa works locally, but not when run on github actions on the same machine
- CSS Imported by a Dependency
- Module '"rxjs"' has no exported member 'firstValueFrom'
- what use spring multiple handler websocket session service
- Failing to increment pair count correctly add_pairs Tideman CS50
- How can I get the average cost from a specific column from a table in R
- The theme system is not working for me and I'm not sure why
- Sorting multiple rows of un-sorted data based on text string – GSheets
- Tkinter RuntimeError: main thread is not in main loop when trying to insert item into listbox from different thread
- SwiftUI: Generating a continuous alphabetical list (from a-z then from aa, bb, cc, …, aaa, bbb, ccc)
- AWS Eventbridge rule trigger once all in-flight sqs messages are processed
- Avoid calling a method in a loop
- How to add a single value in datagridview with c#?
- MenuItem with onClick={popupState.close} in Material-ui V 5.0 how to execute a Link to open the component?
amazon-web-services android angular api arrays c# css dart dataframe django docker excel express firebase flutter html ios java javascript jquery json kotlin laravel linux list mongodb mysql node.js pandas php postgresql python python-3.x r react-native reactjs regex spring spring-boot sql sql-server string swift typescript vue.js