Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 基于旧数据帧创建数据帧_Python 2.7 - Fatal编程技术网

Python 2.7 基于旧数据帧创建数据帧

Python 2.7 基于旧数据帧创建数据帧,python-2.7,Python 2.7,我有一个数据帧: A B C D 0 s 3 a 4 s 2 a 5 s 2 a 6 s 1 a 7 s 2 b 7 s 3 b 6 s 0 b 如何创建如下所示的新数据帧 A B C D 0 4 8 4-a 7 3 5 3-b 新的数据框通过将“D”列的元素分组来汇总旧的数据框,因此“A”是索引

我有一个数据帧:

   A   B   C   D
   0   s   3   a
   4   s   2   a
   5   s   2   a
   6   s   1   a
   7   s   2   b
   7   s   3   b
   6   s   0   b
如何创建如下所示的新数据帧

   A   B   C   D
   0   4   8   4-a
   7   3   5   3-b

新的数据框通过将“D”列的元素分组来汇总旧的数据框,因此“A”是索引,“B”是元素计数,“C”是元素的总和,其中“D”具有相同的值。

好吧,假设您的数据存储在
df
中,这是一个多步骤的过程,可以这样做

import pandas as pd

data = {'A': {0: 0, 1: 4, 2: 5, 3: 6, 4: 7, 5: 7, 6: 6},
        'B': {0: 's', 1: 's', 2: 's', 3: 's', 4: 's', 5: 's', 6: 's'},
        'C': {0: 3, 1: 2, 2: 2, 3: 1, 4: 2, 5: 3, 6: 0},
        'D': {0: 'a', 1: 'a', 2: 'a', 3: 'a', 4: 'b', 5: 'b', 6: 'b'}}
df = pd.DataFrame(data)

# Handling column A (first index per value in D)
output_df = df.drop_duplicates(subset='D', keep='first')

# Itering through rows
for index, row in output_df.iterrows():

    #Calcultating the counts in B
    output_df.loc[index, 'B'] = df[df.D == row.D].B.count()

    #Calcultating the sum in C
    output_df.loc[index, 'C'] = df[df.D == row.D].C.sum()

#Finally changing values in D by concatenating values in B and D
output_df.loc[:, 'D'] = output_df.B.map(str) + "-" +  output_df.D
输出:


到目前为止,你的代码是什么?我正在寻找如何编码它,当我运行我得到的代码时,我只有数据帧df=pd.read_csv(“/data/mydata.txt”,header=None):.local/lib/python2.7/site packages/pandas/core/index.py:543:SettingWithCopyWarning:试图在数据帧的切片副本上设置值。尝试使用.loc[row\u indexer,col\u indexer]=value,请参见文档中的注意事项:self.obj[item]=s结果在
输出数据框中。您只需打印它
print(output_df)
.local/lib/python2.7/site packages/pandas/core/generic.py:5096:SettingWithCopyWarning:试图在数据帧的切片副本上设置值。尝试使用.loc[row\u indexer,col\u indexer]=value,请参见文档中的注意事项:self[name]=value现在我可以看到输出结果,但似乎我有两列,索引“a”和“D”都有一个索引。最后,如果您不想看到
output\u df
的索引,您可以这样做:
print(output\u df.to\u string(index=False))
   A   B   C   D
   0   4   8   4-a
   7   3   5   3-b