【问题标题】:Insert data into grouped DataFrame (pandas)将数据插入分组的 DataFrame (pandas)
【发布时间】:2017-05-19 10:19:27
【问题描述】:

我有一个按某些列分组的熊猫数据框。现在我想将四个相邻列的数值的平均值插入到一个新列中。这就是我所做的:

df = pd.read_csv(filename)
# in this line I extract a unique ID from the filename
id = re.search('(\w\w\w)', filename).group(1)

文件如下所示:

col1   | col2  | col3
-----------------------
str1a  | str1b | float1

我的想法现在如下:

# get the numeric values
df2 = pd.DataFrame(df.groupby(['col1', 'col2']).mean()['col3'].T
# insert the id into a new column
df2.insert(0, 'ID', id)

现在循环遍历所有

for j in range(len(df2.values)):
    for k in df['col1'].unique():
        df2.insert(j+5, (k, 'mean'), df2.values[j])

df2.to_excel('text.xlsx')

但我收到以下错误,指的是带有 df.insert 的行:

TypeError: not all arguments converted during string formatting

if not allow_duplicates and item in self.items:
    # Should this be a different kind of error??
    raise ValueError('cannot insert %s, already exists' % item)

我不确定这里指的是什么字符串格式,因为我只传递了数值。

最终输出应该在一行中包含来自 col3 的所有值(由 id 索引),并且每第五列应该是前面四个值的插入平均值。

【问题讨论】:

  • 你能添加数据样本和想要的输出吗?
  • 我刚做了。我希望它现在更清楚了。
  • 对不起,没有。您可以添加 5 - 6 行数据和所需的输出吗?最好是如果同时出现错误。
  • 您的问题是关于写入 .xlsx 文件还是进行转换?
  • @FabianMoss - 谢谢。也许帮助how to provide a great pandas example

标签: python pandas dataframe insert


【解决方案1】:

如果我不得不处理像你这样的文件,我会编写一个函数来转换为 csv... 类似的东西:

data = []
for lineInFile in file.read().splitlines():
    lineInFile_splited = lineInFile.split('|')
    if len(lineInFile_splited)>1: ## get only data and not '-------'
        data.append(lineInFile_splited)
df = pandas.DataFrame(data, columns = ['A','B'])

希望对您有所帮助!

【讨论】:

  • 我认为它实际上是相反的。我有许多文件,我想从中提取一列并将这些列完全放入一个数据框中。然后我想在特定点插入平均值。
猜你喜欢
  • 2016-05-02
  • 2020-10-04
  • 2018-08-13
  • 1970-01-01
  • 1970-01-01
  • 2013-07-22
  • 1970-01-01
  • 2021-04-12
  • 2014-08-29
相关资源
最近更新 更多