简体   繁体   English

将 Pandas DataFrame 列值从数组更改为数组中的第一个值

[英]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.

相关问题 如何使用pandas数据框的列值更改numpy数组的索引值 - how to change the index value of numpy array with column values of pandas dataframe 计算 pandas dataframe 中每一列的第一个值的增长率并返回 Numpy 数组 - Calculate the growth ratio from first value in every column in a pandas dataframe and return a Numpy array 从熊猫数据框中的字符串数组中获取第一个数值 - Take first numeric value from string array in pandas dataframe 用数组更改列中的所有pandas数据框单元格 - change all pandas dataframe cell in a column with an array 取决于 Pandas Dataframe 列的值数组 - Array of values depending on column of Pandas Dataframe 从numpy数组创建Pandas数据帧,并使用数组的第一列作为索引 - Create Pandas dataframe from numpy array and use first column of the array as index Python pandas dataframe:在数组列中,如果第一项包含特定字符串,则从数组中删除该项 - Python pandas dataframe : In an array column, if first item contains specific string then remove that item from array 将 pandas 数据框列中的每个值与第二个数据框列的所有值相乘并将每个第一个数据框值替换为结果数组 - Multiply each value in a pandas dataframe column with all values of 2nd dataframe column & replace each 1st dataframe value with resulting array 检查数组值并将结果数组作为列添加到熊猫数据框 - Check array values and add resulted array as column to pandas dataframe 从pandas数据框创建np.array,该数据框有一列保存数组索引的值,另一列保存每个索引的值? - Create np.array from pandas dataframe which has a column holding values of the array's indices and another column holding the value at each index?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM