【问题标题】:Lowercasing each word in a pandas dataframe column小写熊猫数据框列中的每个单词
【发布时间】:2015-04-20 20:39:35
【问题描述】:

我是 pandas 的新手,并且在 pandas 数据框中有一列包含我想转换为小写的字符串(非小写)。数据框列被称为:

df['labels']

它的元素都是(字符串的)列表:

0     ["Cat", "Dog", "Horse"]
1     ["Pig", "Fish", "Giraffe"]
....

我想将列表中的每个字符串都小写,直觉上我试过这个:

for element in input_data['labels']:
    for word in element:
        word.lower()

但是在 print(input_data["labels"] 上没有小写。

【问题讨论】:

  • 有什么理由将它们存储为列表?每个列表是否总是只包含 3 个元素?如果是这样,考虑将它们存储在不同的列是否有意义?
  • 字符串是不可变的,所以word.lower() 只会创建一个新字符串。
  • @JohnGalt 每个不一定有 3 个元素,我还有其他原因想要将它们保留在列表中

标签: python-3.x pandas


【解决方案1】:

以下方法可行,但通常将列表存储为 IMO 数据是个坏主意:

In [18]:

df['labels'] = df['labels'].apply(lambda x: [w.lower() for w in x])
df
Out[18]:
                 labels
0     [cat, dog, horse]
1  [pig, fish, giraffe]

【讨论】:

    【解决方案2】:

    这会给你想要的--

    df = pd.DataFrame({'Labels' : [["Cat", "Dog", "Horse"],
                                   ["Pig", "Fish", "Giraffe"]]})
    
    df['Labels'].apply(lambda x: [y.lower() for y in x])
    
    0       [cat, dog, horse]
    1    [pig, fish, giraffe]
    Name: Labels, dtype: object
    

    但是,就像在cmets中提到的那样,你需要这样存储数据吗?

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 2019-10-22
      • 2017-12-18
      相关资源
      最近更新 更多