Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

python - Pandas Dataframe override existing row

I have a pandas dataframe exported to CSV, storing an index, username, and a string specific to the user. I want a function to edit the string of the user if they already exist in the database, and create a user if they don't. For example:

,User,String
0,Bob,Bob Is Cool
1,Joe,Joe Is Great

Adding Joe and Joe is Smart will make it:

,User,String
0,Bob,Bob Is Cool
1,Joe,Joe Is Smart

Adding Jeff and Jeff is Good will make it:

,User,String
0,Bob,Bob Is Cool
1,Joe,Joe Is Smart
2,Jeff,Jeff is Good

I tried using in. For Example:

if user in df.User:
if user in df.values:

And so on but I can't seem to get it to work. It always adds a new entry no matter what.

Any help is appreciated. Thanks in Advance!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

in in pandas check the index of value instead of the value itself:

>>> import pandas as pd
>>> data = pd.read_csv('data.csv', index_col=0)
>>> 'Bob' in data['User']
False
>>> 1 in data['User']
True

if you want to check if Bob exists in the dataframe you have to do this:

>>> 'Bob' in data['User'].values
True

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...