修复数据框中的希腊字母 - Python 2.7

Fixing greek letters in dataframe - Python 2.7

我正在使用 python 2.7,我有一个数据框,其中包含希腊字母,如下所示:

units = ['Ab_alpha_cd', 'XY_beta_zz', 'Ef_gamma_gh']
descriptions = ['Name1 (Ab_alpha_cd): description_1', 'Name2 (XY_beta_zz): description_2', 'Name3 (Ef_gamma_gh): description_3'
df = pd.dataframe
df['units'] = units
df['descriptions'] = descriptions

我需要将描述栏中的 '_greek_' 更改为正确的希腊字母。 我尝试了几种方法:

#first try:
for i in range (0, len(df)):
    df.loc[i,'descriptions'].replace('_alfa_','\u03B1').replace('_beta_','\u03B2').replace('_gamma_','\u03B3')

#second try:
for i in range (0, len(df)):
    df.loc[i,'descriptions'].replace('_alfa_',unichr(945)).replace('_beta_',unichr(946)).replace('_gamma_',unichr(947))

#thrid try
for i in range (0, len(df)):
    df.loc[i,'descriptions'].replace('_alfa_','α').replace('_beta_','β').replace('_gamma_','γ')

#fourth try
for i in range (0, len(df)):
    df.loc[i,'descriptions'].replace('_alfa_','α'.encode('utf-8')).replace('_beta_','β'.encode('utf-8')).replace('_gamma_','γ'.encode('utf-8'))

但没有任何效果。当我调用 df.head() 时,希腊字母不显示。当我尝试将 df 写入 csv 文件时,即使使用 utf-8 编码,它们也不会显示。

我需要最终结果是一个字符串更正后的列表。

我能做什么?

您可以在 documentation 中阅读以下内容:

Dicts can be used to specify different replacement values for different existing values. For example, {'a': 'b', 'y': 'z'} replaces the value ‘a’ with ‘b’ and ‘y’ with ‘z’. To use a dict in this way the value parameter should be None.

示例数据:

import pandas as pd
df = pd.DataFrame({'A': ['Name1 (Ab_alpha_cd): description_1', 'Name2 (XY_beta_zz): description_2', 'Name3 (Ef_gamma_gh): description_3']})

代码:

df['A'].replace({'_alpha_':'α', '_beta_':'β', '_gamma_':'γ'}, regex=True)

输出:

                              A
0  Name1 (Abαcd): description_1
1  Name2 (XYβzz): description_2
2  Name3 (Efγgh): description_3