42piratas
42piratas

Reputation: 595

Appending a value to a specific DataFrame cell

I have tested many different options to append a value to a certain cell in a dataframe, but couldn't figure out yet how to do it, nor have found any relevant on my researches.

I have a series/column of my dataframe that starts with 'False' in all positions. Then it starts receiving value with time, one per time. The problem then starts when I have to add more than one value to the same cell. E.g.

df = pd.DataFrame(data=[[1, 2, False], [4, 5, False], [7, 8, False]],columns=["A","B","C"])

which gives me:

-   A   B   C
0   1   2   False
1   4   5   False
2   7   8   False

I've tried to transform the cell into a list in different ways, e.g (just a few as examples):

df.iloc[0,0] = df.iloc[0,0].tolist().append("A")

OR -

df.iloc[0,0] = df.iloc[0,0].tolist()   
df.iloc[0,0] = df.iloc[0,0].append("A")

But nothing worked so far.

Any way I can append a value (a string) to a specific cell, a cell that might start as a Boolean or as a String?

Upvotes: 3

Views: 9931

Answers (2)

tania
tania

Reputation: 2335

It is generally not advisable (check this article for example) to have Pandas dataframes with mixed dtypes since you cannot guarantee the behaviour of each "cell".

Therefore, one solution would be to first ensure that the whole column that you might change in the future is of type list. For example, if you know that the column "C" will or might be updated in the future to append values to it as if it's a list, then it's preferable that the False values you mentioned as a "starting point" are already encoded as part of a list. For example, with the dataframe you provided:

df.loc[:,"C"] = df.loc[:,"C"].apply(lambda x: [x])
df.iloc[0, 2].append("A")
df

This outputs:

    A   B   C
0   1   2   [False, A]
1   4   5   [False]
2   7   8   [False]

And now, if you want to go through the C and check if the first value is False or True, you could, for example, iterate over:

df["C"].apply(lambda x: x[0])

This ensures that you can still access this value without resorting to tricks like checking the type, etc.

Upvotes: 1

Alexandra Dudkina
Alexandra Dudkina

Reputation: 4472

If it's needed to concat value of a cell with a string value, you can use:

df.iloc[1,0] = str(df.iloc[1,0]) + "A"
df.iloc[0,2] = str(df.iloc[0,2]) + "A"

Or f-string can be used:

df.iloc[1,0] = f'{df.iloc[1,0]}' + "A"
df.iloc[0,2] = f'{df.iloc[0,2]}' + "A"

Upvotes: 2

Related Questions