【问题标题】:How to save values in pandas dataframe after editing some values编辑一些值后如何在熊猫数据框中保存值
【发布时间】:2021-07-09 15:52:22
【问题描述】:

我有一个看起来像这样的数据框(它包含虚拟数据)-

我想删除每个单元格中“_________”标识符之后出现的文本。我编写的代码如下(逻辑:添加一个包含 NaN 的新列并将编辑后的值保存在该列中)-

import pandas as pd
import numpy as np

df = pd.read_excel(r'Desktop\Trial.xlsx')

NaN = np.nan
df["Body2"] = NaN

substring = "____________"

for index, row in df.iterrows():
    if substring in row["Body"]:
        split_string = row["Body"].split(substring,1)
        row["Body2"] = split_string[0]

print(df)

但 Body2 列仍显示 NaN 而不是编辑后的值。

任何帮助将不胜感激!

【问题讨论】:

  • 使用Series.str.split 而不是循环。
  • 使用df["Body2"]=df["Body"].str.split(substring,1).str[0]

标签: python pandas dataframe split


【解决方案1】:
`for index, row in df.iterrows():
    if substring in row["Body"]:
    split_string = row["Body"].split(substring,1)
    #row["Body2"] = split_string[0] # instead use below line         
    df.at[index,'Body2'] = split_string[0]`

利用at来修改值

【讨论】:

    【解决方案2】:

    不要遍历行,而是一次对所有行执行操作。您可以使用 expand 将值拆分为多列,我认为这是您想要的。

    substring = "____________"
    df = pd.DataFrame({'Body': ['a____________b', 'c____________d', 'e____________f', 'gh']})
    df[['Body1', 'Body2']] = df['Body'].str.split(substring, expand=True)
    print(df)
    #              Body Body1 Body2
    # 0  a____________b     a     b
    # 1  c____________d     c     d
    # 2  e____________f     e     f
    # 3              gh    gh  None
    

    【讨论】:

    • 非常好 - 你能为我的答案投票吗?
    猜你喜欢
    • 2019-01-05
    • 2019-07-23
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 2023-03-14
    • 2021-10-25
    • 2022-07-15
    相关资源
    最近更新 更多