简体   繁体   中英

Looping through and modify each element of a column

Given a dataset like this

import pandas as pd
d = {'description': ["abcd","efgh","ijkl"], 'code': ["A","K","Z"]}
df = pd.DataFrame(data=d)


  description   code
0   abcd          A
1   efgh          K
2   ijkl          Z

I'm aiming at getting this

   description  code
0   "abcd"        A
1   "efgh"        K
2   "ijkl"        Z

this code just prints out what I'm aiming at

for row in df["description"]:   #accessing to each row
    print(f'"{row}"')           #"modifying" each row

and this is what generates

"abcd"
"efgh"
"ijkl"

I was trying to set something like this but it's not correct

rows = df.shape[0]
i = 0
while i < rows:
     f'"{df.loc[i,"description"]}"'
#wrong

or something like

df1["description"]=df1["description"].apply(lambda ??

you can try this simply:

df['description1'] = '"'+ df['description'] + '"'
df

  description code description1
0        abcd    A       "abcd"
1        efgh    K       "efgh"
2        ijkl    Z       "ijkl"

With row iteration, you can do something like that:

for i, row in df.iterrows():
  new_val = something
  if <condition>:
    new_val = something_else
  df.at[i,'description'] = new_val

Using your while loop, it would look like this:

rows = df.shape[0]
i = 0
while i < rows:
    df.iloc[i,:]['description'] = '"' + df.iloc[i,:]['description'] + '"'
    i = i+1

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