简体   繁体   中英

How to insert text in a range of row in a specific column in a csv file in pandas?

I want to insert a text in a range of lines in a specific column of a csv file like [2:], I already searched other questions like this on the internet, but none worked for me.

Example:

"File before I insert text"

NAME, AGE
 , 2
 , 3
 , 4
 , 5

"File after I insert a text"

NAME, AGE
 , 2
henrique , 3
henrique , 4
 , 5

My code:

header = ["Name", "Age"]

df = pd.DataFrame(columns=header)
var=df.shape[0]
df.loc[2:, 'Name'] = 'henrique'
df.to_csv("stackoverflow.csv", sep=',
          index=False)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.at.html

To insert data you want to use df.at(2:, 'Name')

df = pd.DataFrame(columns=header)
var=df.shape[0]
df.at(2:, 'Name') = 'henrique'
df.to_csv("stackoverflow.csv", sep=',
          index=False)

However, if you want the following output

NAME, AGE
 , 2
henrique , 3
henrique , 4
 , 5

Then you should use this index

df = pd.DataFrame(columns=header)
var=df.shape[0]
df.at(1:2, 'Name') = 'henrique'
df.to_csv("stackoverflow.csv", sep=',
          index=False)

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