我有两个数据帧: longdf和shortdf。longdf是‘master’列表,我需要基本上匹配从shortdf到Longdf的值,那些匹配的值,替换其他列中的值。longdf和shortdf都需要大量的数据清理。
我们的目标是达到df的“目标”。我正在尝试使用for循环,其中我希望1)提取df单元格中的所有数字,以及2)从单元格中去掉空白/单元格空间。首先:为什么这个for循环不能工作?第二:有没有更好的方法呢?
import pandas as pd
a = pd.Series(['EY', 'BAIN', 'KPMG', 'EY'])
b = pd.Series([' 10wow this is terrible data8 ', '10/ USED TO BE ANOTHER NUMBER/ 2', ' OMG 106 OMG ', ' 10?7'])
y = pd.Series(['BAIN', 'KPMG', 'EY', 'EY' ])
z = pd.Series([108, 102, 106, 107 ])
goal = pd.DataFrame
shortdf = pd.DataFrame({'consultant': a, 'invoice_number':b})
longdf = shortdf.copy(deep=True)
goal = pd.DataFrame({'consultant': y, 'invoice_number':z})
shortinvoice = shortdf['invoice_number']
longinvoice = longdf['invoice_number']
frames = [shortinvoice, longinvoice]
new_list=[]
for eachitemer in frames:
eachitemer.str.extract('(\d+)').astype(float) #extracing all numbers in the df cell
eachitemer.str.strip() #strip the blank/whitespaces in between the numbers
new_list.append(eachitemer)
new_short_df = new_list[0]
new_long_df = new_list[1]
发布于 2019-07-10 23:08:25
如果我理解正确的话,您希望获取一系列包含整数的字符串,并删除所有不是整数的字符。为此,您不需要使用for循环。相反,您可以用一个简单的正则表达式来解决它。
b.replace('\D+', '', regex=True).astype(int)
返回:
0 108
1 102
2 106
3 107
正则表达式用一个空字符串替换所有不是数字的字符(用\D
表示),删除所有不是数字的字符。.astype(int)
将序列转换为整数类型。您可以像往常一样将结果合并到您的最终数据帧中:
result = pd.DataFrame({
'consultant': a,
'invoice_number': b.replace('\D+', '', regex=True).astype(int)
})
https://stackoverflow.com/questions/56973530
复制相似问题