我正在解析.csv file(您可以在此处看到示例文件。)我正在提取第二行和第七行的数据。没问题。这就是我的做法。
import pandas as pd
import numpy as np
df = pd.read_csv("datas.csv", index_col=0, header=None)
d = {'YSS':'Yahoo!リスティング 12月分 12/1〜12/31',
'YDNRT':'Yahoo!リマーケティング 12月分 12/1〜12/31',
'YDN':' Yahoo!ディスプレイネットワーク 12月分 12/1〜12/31',
'GSN':'Googleリスティング 12月分 12/1〜12/31',
'GDNRM':'Googleリマーケティング 12月分 12/1〜12/31',
'GDN':'Googleディスプレイネットワーク 12月分 12/1〜12/31'}
pat = r'({})'.format('|'.join(d.keys()))
df.loc['アカウント名'] = df.loc['アカウント名'].str.extract(pat, expand=False).dropna().map(d)
df.loc['利用額(Fee抜き)'] = df.loc['利用額(Fee抜き)'].astype(str).apply(lambda x: x.split(".")[0])
df1 = df.loc[['アカウント名', '利用額(Fee抜き)']]
df1 = df1.T
df1.columns = ['項目','金額']
df1['数量'] = 1
df1['単位'] = "式"
df1['単価'] = np.nan
wow = df1[['項目','数量','単位','単価', '金額']]
newFile = wow.shift(1)
newFile['項目'] = newFile['項目'].fillna(df.loc['クライアント名'])
newFile.loc[newFile['項目'].str.contains('プレサンス'),['数量','単位','単価', '金額']] = ['','','','']
pos = newFile.index[newFile['項目'].str.contains('プレサンス')]
d = {}
i = 0
for p in pos:
if p == pos[0]:
d[p] = newFile.loc[:pos[i+1]-1].append(pd.Series('',newFile.columns), ignore_index=True)
elif (i + 1) > len(pos) - 1:
d[p] = newFile.loc[pos[i-1]+1:]
else:
d[p] = newFile.loc[p:pos[i+1]-1].append(pd.Series('',newFile.columns), ignore_index=True)
i = i + 1
pd.concat(d, ignore_index=True)
p.to_csv('newfile.csv', index=False)
使用新列创建新的.csv文件。你可以在这里看到它。 https://imgur.com/a/5w63Yht但我需要再做一件事。
在原始的file's行中,第1行包含公司名称。我想解析这些公司名称,并将其放在图像中的每个组的顶部,如图所示:https://imgur.com/a/4T2WxYt也需要删除总金额...
我不太确定是否可能...
答案 0 :(得分:2)
您可以通过索引原始df并调用fillna
来替换列NaN
的{{1}},然后过滤包含字符串'項目'
的行并覆盖该行带有空字符串列表的值,首先我们shift
将行往下移1,这样就形成了标头:
'プレサンス'
现在,当您要添加填充以使其更具可读性时,我们可以存储总计位置的索引位置,然后遍历这些位置并切片df,将其添加到字典中,然后调用concat
垂直堆叠填充的切片:
In[111]:
newFile = df1.shift(1)
newFile['項目'] = newFile['項目'].fillna(df.loc['クライアント名'])
newFile.loc[newFile['項目'].str.contains('プレサンス'),['数量','単位','単価', '金額']] = ['','','','']
newFile
Out[111]:
項目 金額 数量 単位 単価
1 プレサンス ロジェ 和泉中央
2 Yahoo!リスティング 12月分 12/1〜12/31 YSS 91188 1 式 NaN
3 Yahoo!リマーケティング 12月分 12/1〜12/31 25649 1 式 NaN
4 Yahoo!ディスプレイネットワーク 12月分 12/1〜12/31 13211 1 式 NaN
5 Googleリスティング 12月分 12/1〜12/31 131742 1 式 NaN
6 Googleリマーケティング 12月分 12/1〜12/31 35479 1 式 NaN
7 Googleディスプレイネットワーク 12月分 12/1〜12/31 18999 1 式 NaN
8 プレサンス グラン 茨木
9 Yahoo!リスティング 12月分 12/1〜12/31 YSS 113373 1 式 NaN
10 Yahoo!リマーケティング 12月分 12/1〜12/31 28775 1 式 NaN
11 Yahoo!ディスプレイネットワーク 12月分 12/1〜12/31 19010 1 式 NaN
12 Googleリスティング 12月分 12/1〜12/31 158389 1 式 NaN
13 Googleリマーケティング 12月分 12/1〜12/31 45530 1 式 NaN
14 Googleディスプレイネットワーク 12月分 12/1〜12/31 23224 1 式 NaN
15 プレサンス ロジェ 江坂
现在为每个切片创建一个字典,并添加一个空行:
In[112]:
pos = newFile.index[newFile['項目'].str.contains('プレサンス')]
pos
Out[112]: Int64Index([1, 8, 15], dtype='int64')