简体   繁体   English

用熊猫数据框中另一列中的值替换空列表

[英]replace empty list with values in another column in pandas dataframe

I am trying to replace list of values in one column with another column, below is data and script I am using我正在尝试用另一列替换一列中的值列表,下面是我正在使用的数据和脚本

old = [[51, 1], 
          [52, 1], 
          [53, -1], 
          [], 
          [54, 0], 
          [55, 0], 
          [52, 0], 
          [], 
          [52, 0], 
          [54, -1]]

import pandas as pd
df = pd.DataFrame(columns=['old','new'])     
df["old"]=old

new = [[51, 1], 
          [52, 1], 
          [53, -1], 
          [54, -2], 
          [54, 0], 
          [55, 0], 
          [52, 0], 
          [55. -3], 
          [52, 0], 
          [54, -1]]

df["new"]=new

for index, row in df.iterrows():
    if ((df["old"][index])==[]) :
        df.old[index] = df.new[index]

Is there any better way than using for loop , actually in my script there are too many loops so i want to avoid using for loop for few data manipulation If anyone knows that will be great help有没有比使用 for 循环更好的方法,实际上在我的脚本中有太多循环,所以我想避免使用 for 循环进行少量数据操作如果有人知道这将有很大帮助

You can use Series.mask :您可以使用Series.mask

# df['old'] = df['old'].mask(df['old'].str.len() == 0, df['new'])
df['old'].mask(df['old'].str.len() == 0, df['new'])

0     [51, 1]
1     [52, 1]
2    [53, -1]
3    [54, -2]
4     [54, 0]
5     [55, 0]
6     [52, 0]
7      [52.0]
8     [52, 0]
9    [54, -1]
Name: old, dtype: object

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果熊猫数据框列中存在列表值列表,请用另一个熊猫列中的值替换它们 - If list of lists values are present in Pandas dataframe column replace them with values from another Pandas column Pandas 将列的值替换为与另一个 Dataframe 的比较 - Pandas replace values of a column with comparison to another Dataframe 根据另一列的值替换Pandas数据框的Column的值 - Replace values of a Pandas dataframe's Column based on values of another column 根据另一列 Pandas 替换列中的空值 - Replace the empty values in column based on another column Pandas 用另一列 Pandas DataFrame 替换一列中的值 - Replace values from one column with another column Pandas DataFrame 如何在给定条件的情况下用 pandas dataframe 中的另一列替换一列的值 - How to replace the values of a column with another column in pandas dataframe given a condition 使用 Pandas 将特定列值替换为另一个数据框列值 - Replace specific column values with another dataframe column value using Pandas 有效地将值从一列替换到另一列 Pandas DataFrame - Efficiently replace values from a column to another column Pandas DataFrame 如果索引在另一个数据框中而不列出列,熊猫会替换所有列值吗? - Pandas replace all column values if index is in another dataframe without list the columns? 如何用空列表值替换 Pandas 列 NaN 值? - How To Replace Pandas Column NaN Values with Empty List Values?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM