【问题标题】:Change values in a dataframe column with mixed types based on a condition根据条件更改具有混合类型的数据框列中的值
【发布时间】:2022-01-25 23:08:45
【问题描述】:

我的数据集的一列既有字符串又有浮点数。在该列中,对于每个字符串,我尝试仅将其替换为字符串的前 5 个字符。

def isfloat(num):
    try:
        float(num)
        return True
    except ValueError:
        return False

df = pd.DataFrame([[1, "Alligator"], [1, 3], [4, "Markets"]], columns=['A', 'B'])

以下两种方法似乎并没有改变实际的数据框。

df['B'].apply(lambda x: float(x) if isfloat(x) else x[0:5])

for index, row in df.iterrows():
    if not isfloat(row.B):
        row.B = row.B[0:5]

这个下一个方法导致警告“无法将系列转换为”,我认为是因为无法以这种方式调用isfloat方法。

df['B'] = np.where(not isfloat(df['B']), df['B'][0:5], df['B'])

我也尝试使用 .loc,但它似乎不适合,因为我需要根据条件进行更改。一个人会怎么做,或者我错过了什么?

【问题讨论】:

    标签: python pandas dataframe replace conditional-statements


    【解决方案1】:

    我相信你需要:

    df['B']=df['B'].apply(lambda x: float(x) if isfloat(x) else x[0:5])
    

    因为 DataFrame 没有就地编辑。

    输出:

       A      B
    0  1  Allig
    1  1    3.0
    2  4  Marke
    

    【讨论】:

    • 啊,当然,谢谢!
    【解决方案2】:

    您好,首先,数据框没有就地编辑。您只需将 df.B 列的编辑值再次存储在 df.B 列中。

    df.B=df.B.apply(lambda x: float(x) if isfloat(x) else x[0:5])
    

    您也可以使用以下代码:

    import pandas as pd
    df = pd.DataFrame([[1, "Alligator"], [1, 3], [4, "Markets"]], columns=['A', 'B'])
    newlist=[]   
    for v in df.B:
        if type(v)==str:
            newlist.append(v[:5])
        else:
            newlist.append(v)
    df['B']=newlist
    

    【讨论】:

      猜你喜欢
      • 2020-12-01
      • 2015-05-24
      • 2023-02-21
      • 1970-01-01
      • 2018-05-14
      • 2022-11-24
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多