Python 合并相同的标签进行计数
我有一个巨大的数据帧:Python 合并相同的标签进行计数,python,pandas,merge,count,Python,Pandas,Merge,Count,我有一个巨大的数据帧: country1 import1 export1 country2 import2 export2 0 USA 12 82 Germany 12 82 1 Germany 65 31 France 65 31 2 England 74 47 Japan 74 47 3 Japan
country1 import1 export1 country2 import2 export2
0 USA 12 82 Germany 12 82
1 Germany 65 31 France 65 31
2 England 74 47 Japan 74 47
3 Japan 23 55 England 23 55
4 France 48 12 Usa 48 12
export1
和import1
属于country1
export2
和import2
属于country2
我想按国家统计进出口价值
输出可能类似于:
country | total_export | total_import
______________________________________________
USA | 12211221 | 212121
France | 4545 | 5454
...
...
首先使用:
然后汇总总和:
df = df.groupby('country', as_index=False).sum()
print (df)
country import export
0 England 97 102
1 France 113 43
2 Germany 77 113
3 Japan 97 102
4 USA 12 82
5 Usa 48 12
您可以将表格分为两部分并将其连接起来:
func = lambda x: x[:-1] # or lambda x: x.rstrip('0123456789')
data.iloc[:,:3].rename(func, axis=1).\
append(data.iloc[:,3:].rename(func, axis=1)).\
groupby('country').sum()
输出:
@耶斯雷尔lambda x:x.rstrip('0123456789')
yop,明白吗
func = lambda x: x[:-1] # or lambda x: x.rstrip('0123456789')
data.iloc[:,:3].rename(func, axis=1).\
append(data.iloc[:,3:].rename(func, axis=1)).\
groupby('country').sum()
import export
country
England 97 102
France 113 43
Germany 77 113
Japan 97 102
USA 12 82
Usa 48 12