【问题标题】:Python, Pandas DF. Take number from a string and add it to a new columnPython,熊猫 DF。从字符串中获取数字并将其添加到新列
【发布时间】:2021-06-17 12:31:24
【问题描述】:

我有一个 pandas 数据框,其中一列的值如下所示:

>>> df['video_p25_watched_actions']
[{'action_type': 'video_view', 'value': '137520'}]

我想提取值编号,并将其添加到新列中,因此预期结果是:

Index |           video_p25_watched_actions                | p25
-----------------------------------------------------------------
0     | [{'action_type': 'video_view', 'value': '137520'}] | 137520

我创建了一个包含一些原始数据的谷歌表格,以显示它希望它的外观:

https://docs.google.com/spreadsheets/d/1aJDiXFyUIb9gZCA1-pPDxciPQWv0vcCairY-pkdGg_A/edit?usp=sharing

提前谢谢你!

【问题讨论】:

  • 试试这个:import json df['p25'] = df['video_p25_watched_actions'].apply(lambda x : json.loads(x[0])['value'])

标签: python pandas dataframe facebook-insights


【解决方案1】:

由于列中的所有行具有相同的结构,您可以使用这个

df['new_column'] = df['video_p25_watched_actions'].apply(lambda x: ''.join(e for e in x.split(":")[2] if e.isalnum()))

【讨论】:

  • 这会返回错误:'list' object has no attribute 'split'
【解决方案2】:

试试:

df['value']= df['video_p25_watched_actions'].replace(regex=True,to_replace='[^0-9]',value=' ')

仅从 df['video_p25_watched_actions'] 中获取值,其他字母将替换为空格

【讨论】:

  • 请添加有关此代码为何起作用的上下文,以便答案更有用。
  • 这似乎只是生成了列的副本,没有删除任何内容
  • 这几乎就是答案!我现在修好了。需要 astype(str) 。 df['value'] = test_df['video_p25_watched_actions'].astype(str).replace(regex=True,to_replace='[^0-9]',value='')
猜你喜欢
  • 1970-01-01
  • 2021-07-16
  • 2019-11-21
  • 1970-01-01
  • 2021-01-03
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
相关资源
最近更新 更多