How to get first elements of each list in a list of lists
You just iterate as it were a flat list
lists = [[1, 2, 3, 5], [3, 4, 5, 6], [7, 8, 9, 3],[10, 11, 12, 13]]
for l in lists:
if l != []:
print(l[0])
How to get every first element in 2 dimensional list
You can get the index [0]
from each element in a list comprehension
>>> [i[0] for i in a]
[4.0, 3.0, 3.5]
Get access to the first row of a list in R
A=list()
A[[1]]=c(1,2)
A[[2]]=c(3,4)
A[[3]]=c(5,6)
A
# [[1]]
# [1] 1 2
# [[2]]
# [1] 3 4
# [[3]]
# [1] 5 6
I. First Solution using sapply()
function for just first elements
sapply(A,'[[',1)
# [1] 1 3 5
For Getting lets say 1st, 3rd, 4th elements of each nested list. Not applicable in this example
sapply(A,`[`,c(1,3,4))
II. Second Solution using for
loop
for(i in 1:length(A)){
print (A[[i]][1])
}
# [1] 1
# [1] 3
# [1] 5
Accessing every 1st element of Pandas DataFrame column containing lists
You can use map
and a lambda
function
df.loc[:, 'new_col'] = df.A.map(lambda x: x[0])
Python: Fetch first 10 results from a list
list[:10]
will give you the first 10 elements of this list using slicing.
However, note, it's best not to use list
as a variable identifier as it's already used by Python: list()
To find out more about these type of operations you might find this tutorial on lists helpful and the link @DarenThomas provided Explain Python's slice notation - thanks Daren)
Getting the first element from each list in a column of lists
The easiest way is using str.get
# df['new_column'] = df['codes'].str.get(0)
df['new_column'] = df['codes'].str[0]
However, I would suggest a list comprehension for speed, if there are no NaNs:
df['new_column'] = [l[0] for l in df['codes']]
If lists can be empty, you can do something like:
df['new_column'] = [l[0] if len(l) > 0 else np.nan for l in df['codes']]
To handle NaNs with the list comprehension, you can use loc
to subset and assign back.
m = df['codes'].notna()
df.loc[m, 'new_column'] = [
l[0] if len(l) > 0 else np.nan for l in df.loc[m, 'codes']]
Obligatory why-is-list-comp-worth-it link: For loops with pandas - When should I care?
Selecting all rows with the first 5 different values of a list
You can use np.unique
to get the unique values of a list:
first_vals = np.unique(list)[:5]
new_array = []
for index, value in enumerate(list):
if value in first_vals:
new_array.append([index, value])
print(new_array)
Output:
[[0, 0], [1, 0], [2, 1], [3, 0], [4, 2], [5, 1], [6, 3], [10, 4], [11, 4], [12, 1], [14, 3], [15, 1], [16, 3], [17, 2], [18, 3]]
(Note: it's bad practice use names of Python builtins as variable names, e.g. list
Related Topics
Create a Concentric Circle Legend for a Ggplot Bubble Chart
Drawing Minor Ticks (Not Grid Ticks) in Ggplot2 in a Date Format Axis
Plot.Lm Error: $ Operator Is Invalid for Atomic Vectors
Select N Rows Above and Below Match
Shiny: How to Stop Processing Invalidatelater() After Data Was Abtained or at the Given Time
Error in As.Double(Y):Cannot Coerce Type 'S4' to Vector of Type 'Double'
How to Avoid Density Curve Getting Cut Off in Plot
Accessing Functions with a Dot in Their Name (Eg. "As.Vector") Using Rpy2
Filter a Column Which Contains Several Keywords
R Shiny: Plot with Dynamical Size
Combining .Sd with Renamed Variable Messes with Names of .Sd Columns
Stargazer Output Appears Below Text - Rmarkdown to PDF
R: Pivoting Using 'Spread' Function
Ggplot2 Force Y-Axis to Start at Origin and Float Y-Axis Upper Limit
Highlight a Single "Bar" in Ggplot
Population Pyramid Plot with Ggplot2 and Dplyr (Instead of Plyr)