简体   繁体   English

以有效的方式将数据列表替换为 DataFrame

[英]Replacing list of data to DataFrame in efficient way

I'm doing something like this to replace some number-strings to normal number-strings (I need a string because of front 0 in my dataframe )我正在做这样的事情来将一些number-strings替换为普通number-strings (我需要一个字符串,因为我的dataframe中的前 0 )

char_to_repalce = [('1', "1"), ('2', "2"), ('3', "3"), ('4', "4"), ('5', "5"),
                                ('6', "6"), ('7', "7"), ('8', "8"), ('9', "9"), ('0', "0"), ('O', "0")]
            for col in ['phone_number', 'phone_number2']:
                for char in char_to_repalce:
                    try:
                        df_data[col]=df_data[col].replace(char[0], char[1])
                    except:
                        pass

Which is not very effective way I think... There are also a normal numbers as well, but everything is a string as I need strings我认为这不是很有效的方法......也有一个普通的数字,但一切都是一个string ,因为我需要字符串

We have replace function which can accept dict我们已经replace了可以接受dict的 function

df[['phone_number', 'phone_number2']].replace(dict(char_to_repalce), inplace = True , regex=True)

My thought我的想法

df[['phone_number', 'phone_number2']].replace({' ':''}, inplace = True , regex=True)

Given your char_to_replace variable, I would do the following using map :给定您的char_to_replace变量,我将使用map执行以下操作:

replacers = {x[0]:x[1] for x in char_to_replace}
df = pd.DataFrame({'N1':['1','2','2','3','8'],
                   'N2':['9','5','7','0','O']}) 
df['N1'] = df['N1'].map(replacers)
df['N2'] = df['N2'].map(replacers)
print(df)          

Output: Output:

  N1 N2
0  1  9
1  2  5
2  2  7
3  3  0
4  8  0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM