[英]Change Pandas DataFrame column values from array to first value in array
I have a DataFrame with a labels
column.我有一个带有
labels
列的 DataFrame。 The labels
column is currently an array, and I would like to map the entire column to the first item of the array for each row without naively iterating. labels
列当前是一个数组,我想将整列 map 到每一行的数组的第一项,而不是天真地迭代。
For example, if I have 2 rows with labels
values ['1','m'], ['0'], I would like to map the current values to the new values '1','0'.例如,如果我有 2 行带有
labels
值 ['1','m'],['0'],我想将当前值 map 转换为新值 '1','0'。
You can use .str
for this:您可以为此使用
.str
:
df['labels'] = df['labels'].str[0]
However, it (and other possible ways) is essentially just a loop:然而,它(和其他可能的方式)本质上只是一个循环:
df['labels'] = [x[0] for x in df['labels'] ]
I'd recommend doing a loop since you have better control of error handling, eg:我建议做一个循环,因为您可以更好地控制错误处理,例如:
# this handles empty array as well as NaN values
df['labels'] = [x[0] if x else np.nan for x in df['labels']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.