Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.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按多列分组_Python_Pandas_Data Analysis - Fatal编程技术网

Python按多列分组

Python按多列分组,python,pandas,data-analysis,Python,Pandas,Data Analysis,谢谢你的帮助 我有如下数据: city, room_type A, X A, Y A, Z B, X B, Y B, Y 我希望我的最终结果如下: city, count(X), count(Y), count(z) A, 1, 1, 1 B, 1, 2, 0 我按城市分组,我想显示每个城市中每个房间类型的计数 用python熊猫有什么方法可以做到这一点吗?多谢各位 我几年前就学会了SQL,我认为这是可能的。我相信python也能做到这一点。谢谢 您可以与重命名列一起使用: df =

谢谢你的帮助

我有如下数据:

city,  room_type
A, X
A, Y
A, Z
B, X
B, Y
B, Y
我希望我的最终结果如下:

city, count(X), count(Y), count(z) 
A,  1, 1, 1
B,  1, 2, 0
我按城市分组,我想显示每个城市中每个房间类型的计数

用python熊猫有什么方法可以做到这一点吗?多谢各位

我几年前就学会了SQL,我认为这是可能的。我相信python也能做到这一点。谢谢

您可以与
重命名
列一起使用:

df = pd.crosstab(df.city, df.room_type).rename(columns=lambda x: 'count({})'.format(x))
print (df)
room_type  count(X)  count(Y)  count(Z)
city                                   
A                 1         1         1
B                 1         2         0
对于重塑,使用了另一种带有
groupby
和或的解决方案:



耶斯雷尔没有给出解决方案;-)


更多参与

cities = pd.unique(df.city)
room_types = pd.unique(df.room_type)
d1 = pd.DataFrame(
    np.zeros((len(cities), len(room_types)), dtype=int),
    cities,
    room_types
)
for r, c in df.values:
    d1.set_value(r, c, d1.get_value(r, c) + 1)

d1.rename(columns='count({})'.format).rename_axis('city').reset_index()

第一解的变化

from collections import Counter

pd.Series(
    Counter(map(tuple, df.values.tolist()))
).unstack(fill_value=0).rename(
    columns='count({})'.format
).rename_axis('city').reset_index()

如果我的答案或其他答案有用,别忘了。谢谢
s = pd.value_counts([tuple(i) for i in df.values.tolist()])
s.index = pd.MultiIndex.from_tuples(s.index.values, names=['city', None])
s.unstack(fill_value=0).rename(columns='count({})'.format).reset_index()

  city  count(X)  count(Y)  count(Z)
0    A         1         1         1
1    B         1         2         0
cities = pd.unique(df.city)
room_types = pd.unique(df.room_type)
d1 = pd.DataFrame(
    np.zeros((len(cities), len(room_types)), dtype=int),
    cities,
    room_types
)
for r, c in df.values:
    d1.set_value(r, c, d1.get_value(r, c) + 1)

d1.rename(columns='count({})'.format).rename_axis('city').reset_index()
from collections import Counter

pd.Series(
    Counter(map(tuple, df.values.tolist()))
).unstack(fill_value=0).rename(
    columns='count({})'.format
).rename_axis('city').reset_index()