如何将每个条目的出现添加到熊猫数据框?

时间:2020-06-22 14:27:01

标签: python pandas

df1是一个熊猫数据帧,其中包含一列字母和一列整数:

>>> k = pd.DataFrame({
    "a": numpy.random.choice([i for i in "abcde"], 10), 
    "b": numpy.random.choice(range(5), 10)
})
>>> k
   a  b
0  a  1
1  c  2
2  e  1
3  b  3
4  c  2
5  d  2
6  e  2
7  c  3
8  b  0
9  a  3

使用value_counts(),找到字母的数量:

>>> counts = k["a"].value_counts()
>>> counts
c    3
e    2
b    2
a    2
d    1
Name: a, dtype: int64

如何将每个出现添加到相应的行?它应该导致

>>> k
   a  b  count
0  a  1  2
1  c  2  3
2  e  1  2
[...]
9  a  3  2

2 个答案:

答案 0 :(得分:1)

您可以尝试使用Output: Kilometer(x)Value(y) Time 1 3 00:00 2 3.69 00:00 3 4.30 00:00 #here the data from kilometer points 1.2 and 3.5 have been used, because kilometer 3 is between these 4 4.86 00:00 #this is the last datapoint in a set, so the two previous points are used 1 3.8 00:01 2 2.87 00:01 3 1.96 00:01 4 2.5 00:01

transform

答案 1 :(得分:1)

以下是使用<form action="?" method="post" name="form1" id="form1"> Company: <input name="company[]" type="text" id="company[]" value="ABC"><br> Price: <input name="price[]" type="text" id="price[]" value="10"> <br> Company: <input name="company[]" type="text" id="company[]" value="BBC"><br> Price: <input name="price[]" type="text" id="price[]" value="5"> <br> Company: <input name="company[]" type="text" id="company[]" value="BBC"><br> Price: <input name="price[]" type="text" id="price[]" value="20"> <br> Company: <input name="company[]" type="text" id="company[]" value="ABC"><br> Price: <input name="price[]" type="text" id="price[]" value="15"> <br> <input type="submit" name="submit" id="submit" value="Submit"> </form> 的替代方法:

首先,您可以将transform提取到数据框中:

value_counts()

上面的步骤在许多不同的情况下很有用(并且应该很容易知道)。

然后,左联接会将值计数放入原始数据帧:

mycounts = k['a'].value_counts().rename_axis('a').reset_index(name = 'counts')