【问题标题】:Setting String Values of a Pandas Column with Indices使用索引设置 Pandas 列的字符串值
【发布时间】:2020-12-05 21:42:53
【问题描述】:

我正在尝试在我的数据框中生成一个新列,其中为不同的索引值分配了一个字符串。我不够熟练,无法使用循环来完成,所以我尝试了子集和索引,看看是否可以让我的生活更轻松。

df['event_type'] = []

A = df[df['flags'].isin(['A'])].index
B= df[df['flags'].isin(['B'])].index
C = df[df['flags'].isin(['B'])].index


df.loc[A, 'event_type'] = 'Condition One'
df.loc[B, 'event_type'] = 'Condition Two'
df.loc[C, 'event_type'] = 'Condition Three'

我已经多次得到值的长度与索引的长度不匹配,并且 Index.name 必须是可散列类型错误好几次了。我只想将这些字符串分配给新列中的这些索引,列中的所有其他值都可以是 Nan。

【问题讨论】:

    标签: python pandas string dataframe indexing


    【解决方案1】:

    你可以使用Series.map

    df['event_type'] = df.flags.fillna('').map(
        {"A": "Condition One", "B": "Condition Two", "C": "Condition Three"}
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-20
      • 2019-11-09
      • 2019-10-29
      • 1970-01-01
      • 2020-06-04
      • 1970-01-01
      • 2018-08-02
      相关资源
      最近更新 更多