Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.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,将id-date相同但值不同的行合并到一列中_Python_Pandas_Dataframe - Fatal编程技术网

Python,将id-date相同但值不同的行合并到一列中

Python,将id-date相同但值不同的行合并到一列中,python,pandas,dataframe,Python,Pandas,Dataframe,我选择了有和没有提到“Korona”的行,并按日期进行计数。有些日期没有科罗纳的真实性。 数据帧看起来像: 表1 出版日期 科罗纳 计数 242 2020-06-01 假的 13 243 2020-06-01 真的 3. 244 2020-06-02 假的 7. 245 2020-06-02 真的 1. 246 2020-06-03 假的 11 247 2020-06-04 假的 8. 248 2020-06-04 真的 1. 249 2020-06-05 假的 10 250 2020-06-0

我选择了有和没有提到“Korona”的行,并按日期进行计数。有些日期没有科罗纳的真实性。 数据帧看起来像:

表1

出版日期 科罗纳 计数 242 2020-06-01 假的 13 243 2020-06-01 真的 3. 244 2020-06-02 假的 7. 245 2020-06-02 真的 1. 246 2020-06-03 假的 11 247 2020-06-04 假的 8. 248 2020-06-04 真的 1. 249 2020-06-05 假的 10 250 2020-06-06 假的 5. 251 2020-06-07 假的 5. 252 2020-06-08 假的 14
请尝试使用透视表

d = ''' Published_date  Korona  Count
242 2020-06-01  False   13
243 2020-06-01  True    3
244 2020-06-02  False   7
245 2020-06-02  True    1
246 2020-06-03  False   11
247 2020-06-04  False   8
248 2020-06-04  True    1
249 2020-06-05  False   10
250 2020-06-06  False   5
251 2020-06-07  False   5
252 2020-06-08  False   14'''

df = pd.read_csv(io.StringIO(d), sep='\s+', engine='python')

# pivot the data and reset the index
df1 = pd.pivot_table(df, values='Count', index=['Published_date'],
                    columns=['Korona'], aggfunc=np.sum, fill_value=0).reset_index()
# rename the columns to what you want
df1.columns = ['Published_date', 'Count-NoKorona', 'Count-Korona']
# sum the values into a new column
df1['Count-All'] = df1[['Count-NoKorona', 'Count-Korona']].sum(axis=1)
输出:

  Published_date  Count-NoKorona  Count-Korona  Count-All
0     2020-06-01              13             3         16
1     2020-06-02               7             1          8
2     2020-06-03              11             0         11
3     2020-06-04               8             1          9
4     2020-06-05              10             0         10
5     2020-06-06               5             0          5
6     2020-06-07               5             0          5
7     2020-06-08              14             0         14

非常感谢你,它就像一个符咒:)