【问题标题】:How to get dataframe column value and replace?如何获取数据框列值并替换?
【发布时间】:2017-07-11 09:41:14
【问题描述】:
id  name   country
1   AAA    Afghanistan
2   BBB    Australia

这是我的数据框↑

如何让国家变成↓

id  name   country       Newcountry
1   AAA    Afghanistan   Afg
2   BBB    Australia     Aus

我想从国家列值中获取 3 个单词并添加到 Newcountry 列,怎么办?

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    你可以:

    In [7]: df['Newcountry'] = df['country'].str[:3]
    
    In [8]: df
    Out[8]: 
       id name      country Newcountry
    0   1  AAA  Afghanistan        Afg
    1   2  BBB    Australia        Aus
    

    【讨论】:

      【解决方案2】:

      您可以使用apply()

      df['Newcountry'] = df['country'].apply(lambda x:x[:3])
      

      或者您可以使用属性访问。

      df['Newcountry'] = df1.country.apply(lambda x:x[:3])
      

      【讨论】:

      • 感谢您的回答,它也有效。但我不确定“lambda x:x[:3]”是什么意思?你能给我一些描述吗?
      • lambda 是单行函数。当您申请df['country'] 时,它会逐个迭代每个元素,因此x 具有所有元素迭代df['country'] 字段和x:x[:3] 分配切片值,例如:country='Afghanistan' 然后 x[:3]= 'Afg'。
      • 希望你明白了,如果我的回答对你有帮助别忘了标记。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 2020-10-14
      • 2018-01-28
      相关资源
      最近更新 更多