Home > Net >  Put row value in quotes, based on values in other row
Put row value in quotes, based on values in other row

Time:12-14

I have a dataframe like this (Dots represent spaces):

     Col1   | Col2     | Col3
  ------------------------------------
0 |  ..Val1 | ....Val2 | ...Val3
1 |  6      | 8        | 7

First row contains values with spaces. The spaces must be retained.

Second row contains numeric values that tell how long the values in the first line are.

I want the values in the first row to be enclosed in quotes based on the values in the second row. (value space).

The final result should look like this:

     Col1     | Col2       | Col3
  ----------------------------------------
0 |  "..Val1" | "....Val2" | "...Val3"
1 |  6        | 8          | 7

CodePudding user response:

You can do like this if the first row is generated by second row :

import pandas as pd
df = pd.DataFrame({'Col1': ['', 6], 'Col2': ['', 8], 'Col3': ['', 7]})
#print original df
print(df)
#Get Second row
df_second_row = df.iloc[1]
for i in range(0,len(df_second_row)):
    # Create New str
    new_str = "Val" str(i 1)
    # Calculate number of dot 
    dot_value = df_second_row[i] - len(new_str)
    print("Add for " new_str ": " str(dot_value) " dots")
    # Create new value for first row based on second row
    df.iloc[0][i] = '"'  '{:.>{width}}'.format(new_str, width=df_second_row[i])  '"' 

#Final output
print(df)

Result :

Col1 Col2 Col3 
0  
1    6    8    7
Add for val1: 2 dots
Add for val2: 4 dots
Add for val3: 3 dots
      Col1      Col2     Col3 
0  "..Val1"  "....Val2"  "...Val3" 
1         6           8          7
  • Related