【发布时间】: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