Trying to change a single value in pandas dataframe
.loc
is an indexer. It looks for an entry in the index, but the column name
is not an index. It is simply a column. The following solutions would work:
df.loc[4, 'rating'] = 100 # Because 4 is in the index, but how do you know?
or:
df.loc[df['name']=='cheerio', 'rating'] = 100 # Find the row by column
or:
df.set_index('name', inplace=True) # Make 'name' the index
df.loc['cheerios', 'rating'] = 100 # Use the indexer
Set value for particular cell in pandas DataFrame using index
RukTech's answer, df.set_value('C', 'x', 10)
, is far and away faster than the options I've suggested below. However, it has been slated for deprecation.
Going forward, the recommended method is .iat/.at
.
Why df.xs('C')['x']=10
does not work:
df.xs('C')
by default, returns a new dataframe with a copy of the data, so
df.xs('C')['x']=10
modifies this new dataframe only.
df['x']
returns a view of the df
dataframe, so
df['x']['C'] = 10
modifies df
itself.
Warning: It is sometimes difficult to predict if an operation returns a copy or a view. For this reason the docs recommend avoiding assignments with "chained indexing".
So the recommended alternative is
df.at['C', 'x'] = 10
which does modify df
.
In [18]: %timeit df.set_value('C', 'x', 10)
100000 loops, best of 3: 2.9 µs per loop
In [20]: %timeit df['x']['C'] = 10
100000 loops, best of 3: 6.31 µs per loop
In [81]: %timeit df.at['C', 'x'] = 10
100000 loops, best of 3: 9.2 µs per loop
Replace single value in a pandas dataframe, when index is not known and values in column are unique
Regardless of the performance, you should be able to do this using loc
with boolean indexing
:
df = pd.DataFrame([[5, 2], [3, 4]], columns=('a', 'b'))
# modify value in column b where a is 3
df.loc[df.a == 3, 'b'] = 6
df
# a b
#0 5 2
#1 3 6
How to change a single value in a data frame in R
We need to extract the column
elo_score$elo_score[elo_score$Tm == "BRK"] <- 1000
"Tm" == "BRK"
does a comparison of two strings i.e. "Tm" with "BRK" and not the values of the column "Tm". For that either elo_scores[["Tm"]]
or elo_scores$Tm
or elo_scores[, "Tm"]
(if it is data.frame
) would work
How to get a single value as a string from pandas data frame
If you can guarantee only one result is returned, use loc
and call item
:
>>> df.loc[df['Host'] == 'a', 'Port'].item()
'b'
Or, similarly,
>>> df.loc[df['Host'] == 'a', 'Port'].values[0]
'b'
...to get the first value (similarly, .values[1]
for the second). Which is better than df.loc[df['Host'] == 'a', 'Port'][0]
because, if your DataFrame looks like this,
Host Port
1 a b
Then "KeyError: 0" will be thrown—
df.loc[df['Host'] == 'a', 'Port'][0]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Alternatively, use at
:
>>> df.at[df['Host'].eq('a').idxmax(), 'Port']
'b'
The drawback is that if 'a' doesn't exist, idxmax
will return the first index (and return an incorrect result).
How do I change a single index value in pandas dataframe?
You want to do something like this:
as_list = df.index.tolist()
idx = as_list.index('Republic of Korea')
as_list[idx] = 'South Korea'
df.index = as_list
Basically, you get the index as a list, change that one element, and the replace the existing index.
How to replace a single value in a list of data frames
First of all, the way you created the data frame will cause the columns of the data frames to be all factor. I modified your code as follows to make the first data frame to be factor and the second data frame to be character.
dat_1 <- data.frame(x = c("A", "B", "C", "D"))
dat_2 <- data.frame(x = c("A", "B", "C", "D"), stringsAsFactors = FALSE)
dat <- list("dat_1" = dat_1, "dat_2" = dat_2)
We can use the following code to replace all "C" to be NA
.
dat2 <- lapply(dat, function(x){
x[] <- lapply(x, function(x) replace(x, x %in% "C", NA))
return(x)
})
dat2
# $dat_1
# x
# 1 A
# 2 B
# 3 <NA>
# 4 D
#
# $dat_2
# x
# 1 A
# 2 B
# 3 <NA>
# 4 D
The code will not change the column types.
lapply(dat2, function(x) sapply(x, class))
# $dat_1
# x
# "factor"
#
# $dat_2
# x
# "character"
Related Topics
Filtering Observations in Dplyr in Combination with Grepl
Plotting Cumulative Counts in Ggplot2
Rolling Window Over Irregular Time Series
How to Display Widgets Inline in Shiny
How to Properly Document S4 "[" and "[<-" Methods Using Roxygen
Cannot Coerce Type 'Closure' to Vector of Type 'Character'
Counting Unique Items in Data Frame
Automated Ggplot2 Example Gallery in Knitr
Error When Using Dplyr Inside of a Function
Dodging Points and Error Bars with Ggplot
Using Parlapply and Clusterexport Inside a Function
Geom_Point() and Geom_Line() for Multiple Datasets on Same Graph in Ggplot2
Dynamically Converting a List of Excel Files to CSV Files in R
Arrange a Grouped_Df by Group Variable Not Working
Shade Region Between Two Lines with Ggplot
Remove Plot Margins in Ggplot2
Add Annotation and Segments to Groups of Legend Elements
How to Show the Progress of Code in Parallel Computation in R