I want to get the statistics of a long column, but I have the problems that in the colomn are diffrent datas( A,B,C,D.. ) and the same values ( 2 ) that I will count.
Example:
A
2
2
2
2
B
2
2
C
D
E
2
2
Output will be like:
A 4
B 2
C
D
E 2
Check where the Series
, s
, equals your magic number. Form groups after masking by that same check, but forward filling.
u = s.eq('2') # `2` if it's not a string
u.groupby(s.mask(u).ffill()).sum()
A 4.0
B 2.0
C 0.0
D 0.0
E 2.0
dtype: float64
Input data:
import pandas as pd
s = pd.Series(list('A2222B22CDE22'))
I am assuming that we are working with a text file. ('test_input.txt')
import pandas as pd
data = pd.read_csv('test_input.txt', header=None)
data = list(data[0])
final_out = dict()
last_item = None
for item in data:
try:
item = int(item)
except ValueError:
item = str(item)
if isinstance(item, str):
last_item = item
final_out[last_item] = 0
if isinstance(item, int):
final_out[last_item] += 1
print(final_out)
## {'A': 4, 'B': 2, 'C': 0, 'D': 0, 'E': 2}
print(pd.DataFrame.from_dict(final_out, orient='index'))
## 0
## A 4
## B 2
## C 0
## D 0
## E 2
# For order column, create first.
dataframe = dataframe.rename(columns={0:'unique'})
print(dataframe)
# Ordering
dataframe = dataframe.sort_values(by=['unique'])
print(dataframe)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.