【问题标题】:Inserting data into a cell in pandas将数据插入熊猫中的单元格
【发布时间】:2021-06-15 22:57:46
【问题描述】:

我有一个人的数据框,而不是在 excel 中编辑它,我希望能够直接在 pandas 中输入数据。

在下面的示例表中,John 在df['Group'] 中没有任何内容

DF

Name ID Grade Group
0 John 001 89 Nan
1 Jane 002 56 Group 1
2 Joan 003 91 Group 2
3 David 004 45 Group 1

我希望能够将其更改为“第 4 组”,最好不使用 iloc(这是一个很大的 df)。

Name ID Grade Group
0 John 001 89 Group 4
1 Jane 002 56 Group 1
2 Joan 003 91 Group 2
3 David 004 45 Group 1

我试过了

df.loc[df['Name'] == 'John']['Group'] = 'Group 4'

df2.loc[0,'Group'] = 'Group 4'

这些不起作用(对你来说可能很明显)。

有没有办法做到这一点?

【问题讨论】:

  • df.loc[df['Name'] == 'John','Group'] = 'Group 4'.
  • df.loc[df['Name'] == 'John','Group'] = 'Group 4' if you want to do it by Name of df.Group.fillna('Group 4',inplace=True) if you want to fill all 'NaN's (确保它是 NaN) 在 Group 列中是 'Group4'

标签: python pandas dataframe


【解决方案1】:

要在 pandas 中分配新变量,您可以使用 locat 方法,方法是使用标签名称:

loc方法:

df.loc[df['name'] == 'John', 'Group'] = 'Group 4'

at 方法(警告:at 一次只能访问一个值)

df.at[df['name'] == 'John', 'Group'] = 'Group 4'
# **OR**
df.at[0, 'Group'] = 'Group 4'

【讨论】:

    猜你喜欢
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 2021-01-08
    • 2022-01-12
    • 2016-01-28
    • 2018-01-24
    相关资源
    最近更新 更多