python - 使用替换链更新 pandas 列名称无法正常工作

标签 python pandas

我们有以下列名称:

our_df.columns
Index(['Rank', 'Album', 'Artist', 'Label', 'Label Description',
       'Peak Position', 'Last Week Rank', 'Last 2 Week Rank', 'Weeks On Chart',
       'TW Total Activity', '% CHG', 'LW Total Activity', 'TW Album Sales',
       'TW Song Sales', 'TW TEA', 'TW Audio Streaming Activity',
       'TW Video Streaming Activity', 'TW Total SEA (Audio + Video)', 'ATD'],
      dtype='object')

我们想做这样的事情:

our_df.columns.str.replace(' ','_').replace('.', '').replace('+/-','plus_minus').lower()

...我们首先进行所有替换,然后将所有内容转换为小写。但是,此操作失败,并出现错误'Index' object has no attribute 'replace'。我们已将其更新为

our_df.columns.str.replace(' ','_').str.replace('.', '')

# and get the warning
FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will *not* be treated as literal strings when regex=True.

最后,当我们尝试时

our_df.columns.str.replace(' ','_').str.replace('.', '').str.replace('+/-','plus_minus').str.lower()

...我们收到错误在位置 0 没有可重复的内容

  1. 每次 .replace() 调用之间是否需要重复 str.
  2. 我们如何解决 future 的警告?
  3. 最后一个错误是由 .replace('+/-','plus_minus') 引起的,因为列中没有 +/-。我们如何处理这个问题,而不是抛出错误,而是简单地不进行替换?
  4. 我这样做对吗?

最佳答案

如果要使用str.replace需要重复它,对于+.需要转义\因为正则表达式特殊字符并添加regex=True以删除 future 警告:

(our_df.columns.str.replace(' ','_', regex=True)
               .str.replace('\.', '', regex=True)
               .str.replace('\+/-','plus_minus', regex=True)
               .str.lower())

或者如果传递字典将值转换为Series,因为错误:

AttributeError: 'Index' object has no attribute 'replace'


c = ['Rank', 'Album', 'Artist', 'Label', 'Label Description',
       'Peak Position', 'Last Week Rank', 'Last 2 Week Rank', 'Weeks On Chart',
       'TW Total Activity', '% CHG', 'LW Total Activity', 'TW Album Sales',
       'TW Song Sales', 'TW TEA', 'TW Audio Streaming Activity',
       'TW Video Streaming Activity', 'TW Total SEA (Audio +/- Video)', 'ATD']
our_df = pd.DataFrame(columns=c)

our_df.columns = our_df.columns.to_series().replace({'\s+':'_','\.': '','\+/-':'plus_minus'}, regex=True).str.lower()
print (our_df)
Empty DataFrame
Columns: [rank, album, artist, label, label_description, peak_position, last_week_rank, last_2_week_rank, weeks_on_chart, tw_total_activity, %_chg, lw_total_activity, tw_album_sales, tw_song_sales, tw_tea, tw_audio_streaming_activity, tw_video_streaming_activity, tw_total_sea_(audio_plus_minus_video), atd]
Index: []

关于python - 使用替换链更新 pandas 列名称无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70087562/

相关文章:

python - 将 QListView 与 Pyside 中定义的模型一起使用

python - 考虑基线值,根据具体条件减去和添加值

python - pandas - 高效的迭代和替换

pandas - 将数字上限/阈值应用于 pandas 数据框

python - 多次执行时OpenCV 'cvtColor'改变颜色和饱和度(python)

python - 如何在 python distutils 中包含隐藏文件?

python - Julia 的 `@edit` 宏的 Python 等价物是什么?

python - PyQt:激活 QListWidget 项目

python - seaborn 热图颜色图

pandas - 具有两个 Y 轴和公共(public) X 轴的 Matplotlib 条形图