我正在开发一个原始的excel文件来开发一个有组织的格式数据库(.xlsx)格式。演示输入文件如下:输入文件
FromTo B# Bname Id Mend
1 to 2 123 bus1 1 F
1 to 3 234 bus2 1 F
5 to 6 321 bus3 2 F
9 to 10 322 bus5 2 F
1 to 2 326 bus6 1 F
1 to 2 457 bus7 1 F
5 to 6 656 bus8 1 F
9 to 10 780 bus9 2 F
1 to 3 875 bus10 2 F
1 to 3 564 bus11 2 F所需的输出格式如下:输出格式
本质上,我希望自动化输入的列'FromTo‘(基于单元格值)上的过滤器方法,并将其他列的信息按原样放置,如输出格式图像所示。
对于输出,我能够按正确的顺序和格式获得B到E列。为此,我使用了以下使用熊猫的逻辑
import pandas as pd
df = pd.read_excel('st2_trial.xlsx')
#create an empty dataframe
df_1 = pd.DataFrame()
ai = ['1 to 2','1 to 3','5 to 6', '9 to 10'] #all entries from input Col 'FromTo'
for i in range(len(ai)):
filter_ai = (df['FromTo'] == (ai[i]))
df_ai = (df.loc[filter_ai])
df_1 = pd.concat([df_1,df_ai])
print(df_1)从此代码中获取以下输出:
FromTo B# Bname Id Mend
1 to 2 123 bus1 1 F
1 to 2 326 bus6 1 F
1 to 2 457 bus7 1 F
1 to 3 234 bus2 1 F
1 to 3 875 bus10 2 F
1 to 3 564 bus11 2 F
1 to 3 893 bus12 1 F
5 to 6 321 bus3 2 F
5 to 6 656 bus8 1 F
5 to 6 212 bus13 2 F
9 to 10 322 bus5 2 F
9 to 10 780 bus9 2 F但是,很明显,第一列不是我想要的方式!我期待避免'1到2','1至3‘等冗余条目在第一栏。
我相信这可以通过为第一个输出列适当的循环来实现。任何与此相同的帮助将受到高度赞赏!
PS:我想做点什么来解决这个问题:
-create empty dataframe
-list of all unique entries of column 'FromTo'
-take first element of the list put in first column of output
-Then go over my logic to get other required information as it is in loop这样,我认为它将避免输出的第一列中的冗余项。
发布于 2022-07-01 00:48:19
如果不是如何打印groupby对象的话,上面的问题看起来很相似。不过,如果有帮助的话,我会在这里张贴我的答案。
import pandas as pd
df = pd.read_excel('st2_trial.xlsx')
df_group = df.groupby('FromTo').apply(lambda a: a.drop('FromTo', axis = 1)[:].reset_index(drop = True))
print(df_group)
OUTPUT:
B# Bname Id Mend
FromTo
1 to 2 0 123 bus1 1 F
1 326 bus6 1 F
2 457 bus7 1 F
1 to 3 0 234 bus2 1 F
1 875 bus10 2 F
2 564 bus11 2 F
5 to 6 0 321 bus3 2 F
1 656 bus8 1 F
9 to 10 0 322 bus5 2 F
1 780 bus9 2 F发布于 2022-06-30 23:50:44
您可以尝试这样的方法来获得预期的输出:
df_group = df_1.groupby('FromTo')
print(df_group)https://stackoverflow.com/questions/72823087
复制相似问题