Python 是否有相当于tidyr'的熊猫;有多少?
假设我们有一个包含变量分组及其频率的表: 在R中:Python 是否有相当于tidyr'的熊猫;有多少?,python,r,pandas,Python,R,Pandas,假设我们有一个包含变量分组及其频率的表: 在R中: Python/Pandas中是否有等效项?您有一个行索引,并根据计数重复它,例如在R中,您可以执行以下操作: df[rep(1:nrow(df),df$cases),] 首先要获得像您这样的数据: df = pd.DataFrame({'x':[1,1,2,2,2,2],'y':[0,1,0,1,1,1]}) counts = df.groupby(['x','y']).size().reset_index() counts.columns
Python/Pandas中是否有等效项?您有一个行索引,并根据计数重复它,例如在R中,您可以执行以下操作:
df[rep(1:nrow(df),df$cases),]
首先要获得像您这样的数据:
df = pd.DataFrame({'x':[1,1,2,2,2,2],'y':[0,1,0,1,1,1]})
counts = df.groupby(['x','y']).size().reset_index()
counts.columns = ['x','y','n']
x y n
0 1 0 1
1 1 1 1
2 2 0 1
3 2 1 3
然后:
我还没有在Python中找到一个等价的函数,但这是可行的
df2 = df.pop('cases')
df = pd.DataFrame(df.values.repeat(df2, axis=0), columns=df.columns)
df['cases']
被传递到df2
,然后您创建一个新的数据帧,根据df2
中的计数重复原始数据帧中的元素。如果有帮助,请告诉我。除了其他解决方案外,您还可以将获取
、重复
和删除
:
import pandas as pd
df = pd.DataFrame({'Cough': [True, False, True],
'Fever': [False, False, True],
'cases': [1, 2, 3]})
df.take(df.index.repeat(df.cases)).drop(columns="cases")
Cough Fever
0 True False
1 False False
1 False False
2 True True
2 True True
2 True True
使用
tidyr
的API时尽可能简单:
>>从datar.all导入f、tribble、uncount
>>>df=tribble(
…咳嗽,发烧,病例,
…对,错,1,
…假,假,2,
…真的,真的,3
... )
>>>取消计数(df,f.案例)
咳嗽热
0对错
1假1假
2假假
3对对对
4对对对
5对对对
我是这个包裹的作者。如果您有任何问题,请随时提交问题
counts.iloc[np.repeat(np.arange(len(counts)),counts.n),:2]
x y
0 1 0
1 1 1
2 2 0
3 2 1
3 2 1
3 2 1
df2 = df.pop('cases')
df = pd.DataFrame(df.values.repeat(df2, axis=0), columns=df.columns)
import pandas as pd
df = pd.DataFrame({'Cough': [True, False, True],
'Fever': [False, False, True],
'cases': [1, 2, 3]})
df.take(df.index.repeat(df.cases)).drop(columns="cases")
Cough Fever
0 True False
1 False False
1 False False
2 True True
2 True True
2 True True