Replace strings with list elements

Asked

Viewed 65 times

3

# Código
list = [a for a in range(100,103)]
df = pd.DataFrame({
    "A":['x','y','z'],
    "B":[0,1,2],
    "C":[0,0,0]
})

I need to replace column strings C by the strings of list, so that the first string of list replace the first string of the column C, the second string of list replace the second string of the column C.

I tried to apply a replace, but in the substitution all strings of the list inside each string in the column C, staying that way:

0    [100, 101, 102]
1    [100, 101, 102]
2    [100, 101, 102]

The result I wish would be this:

    A   B   C
0   x   0   100
1   y   1   101
2   z   2   102

1 answer

4


Just replace the column in Dataframe. Avoid using the identifiers of builtins of language as variable names.

Example:

import pandas as pd 

l = list(range(100,103))


df = pd.DataFrame({
    "A":['x','y','z'],
    "B":[0,1,2],
    "C":[0,0,0]
})

df["C"] = l

print(df)

Upshot:

   A  B    C
0  x  0  100
1  y  1  101
2  z  2  102

Or use .Loc to access a group of rows and columns by a label.

import pandas as pd 

l = list(range(100,103))


df = pd.DataFrame({
    "A":['x','y','z'],
    "B":[0,1,2],
    "C":[0,0,0]
})

df.loc[:, "C"] = l

print(df)

Upshot:

   A  B    C
0  x  0  100
1  y  1  101
2  z  2  102

See the examples on COLAB

  • 1

    Thank you, simple and fast

Browser other questions tagged

You are not signed in. Login or sign up in order to post.