【发布时间】:2016-07-20 22:26:20
【问题描述】:
我的目标是能够按列值对 CSV 文件的行进行分组,并执行逆运算。举个例子,希望能够在这两种格式之间来回转换:
uniqueId, groupId, feature_1, feature_2
1, 100, text of 1, 10
2, 100, some text of 2, 20
3, 200, text of 3, 30
4, 200, more text of 4, 40
5, 100, another text of 5, 50
按 groupId 分组:
uniqueId, groupId, feature_1, feature_2
1|2|5, 100, text of 1|some text of 2|another text of 5, 10|20|50
3|4, 200, text of 3|more text of 4, 30|40
分隔符(此处为 |)假定不存在于数据中的任何位置。
我正在尝试使用 Pandas 来执行此转换。到目前为止,我的代码可以访问按 groupId 分组的行的单元格,但我不知道如何填充新的数据框。
如何完成我的方法以完成转换为所需的新df?
将新的 df 转换回原始的逆向方法是什么样子的?
如果 R 是这项工作的更好工具,我也愿意接受 R 中的建议。
import pandas as pd
def getGroupedDataFrame(df, groupByField, delimiter):
''' Create a df with the rows grouped on groupByField, values separated by delimiter'''
groupIds = set(df[groupByField])
df_copy = pd.DataFrame(index=groupIds,columns=df.columns)
# iterate over the different groupIds
for groupId in groupIds:
groupRows = df.loc[df[groupByField] == groupId]
# for all rows of the groupId
for index, row in groupRows.iterrows():
# for all columns in the df
for column in df.columns:
print row[column]
# this prints the value the cell
# here append row[column] to its cell in the df_copy row of groupId, separated by delimiter
【问题讨论】: