Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - How to create a new csv file with only modified datas?(Pandas)

I want to create a new csv file with only modified datas. The input csv file is of example as enter image description here

input.csv

Now I want to create a new csv file of modified datas only like

output.csv

The condition is :

df1.loc[df1['Code'].astype(str).str.len() >12, 'Code']= '0'

What I've tried is

import pandas as pd

df1 = pd.read_csv('input.csv')
df1.loc[df1['Code'].astype(str).str.len() >12, 'Code']= ''


df2 = df1.reindex(['ID','Name','Code','Changed Code'],axis=1)

How to create a new dataframe for modified datas in this case? Any suggestions or ideas?

question from:https://stackoverflow.com/questions/65661760/how-to-create-a-new-csv-file-with-only-modified-dataspandas

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

1 Answer

0 votes
by (71.8m points)

This solved my problem.

import pandas as pd

df1 = pd.read_csv('input.csv')


df2 = df1.loc[df1['Code'].astype(str).str.len() >12]
df2 = df2.reindex(['Id','Name','Code','Changed Code'],axis=1)

df2.loc[df2['Code'].astype(str).str.len() >12,'Changed Code']='0'
df2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...