programing

판다의 여러 데이터 프레임 열에서 "별도로" 선택하는 방법은 무엇입니까?

instargram 2023. 7. 11. 21:27
반응형

판다의 여러 데이터 프레임 열에서 "별도로" 선택하는 방법은 무엇입니까?

SQL과 동일한 작업을 수행할 수 있는 방법을 찾고 있습니다.

SELECT DISTINCT col1, col2 FROM dataframe_table

판다 SQL 비교는 아무것도 가지고 있지 않습니다.distinct.

.unique()하나의 열에만 사용할 수 있기 때문에 열을 콘택하거나 목록/튜플에 넣고 비교할 수 있을 것 같습니다. 하지만 이것은 팬더가 좀 더 기본적인 방법으로 해야 할 것처럼 보입니다.

제가 뭔가 명백한 것을 놓치고 있는 것일까요, 아니면 이것을 할 방법이 없을까요?

이 방법을 사용하여 DataFrame의 고유 행을 가져올 수 있습니다.

In [29]: df = pd.DataFrame({'a':[1,2,1,2], 'b':[3,4,3,5]})

In [30]: df
Out[30]:
   a  b
0  1  3
1  2  4
2  1  3
3  2  5

In [32]: df.drop_duplicates()
Out[32]:
   a  b
0  1  3
1  2  4
3  2  5

또한 다음을 제공할 수 있습니다.subset고유성을 확인하기 위해 특정 열만 사용하려는 경우 키워드 인수.문서 문자열을 참조하십시오.

저는 다른 해결책들을 시도해 보았습니다.첫 번째는 다음과

a_df=np.unique(df[['col1','col2']], axis=0)

개체 데이터가 아닌 경우에도 잘 작동합니다. 오류를 방지하는 또 다른 방법은 drop_dupplicates()를 적용하는 것입니다.

a_df=df.drop_duplicates(['col1','col2'])[['col1','col2']]

SQL을 사용하여 이 작업을 수행할 수도 있지만, 제 경우에는 매우 느리게 작동했습니다.

from pandasql import sqldf
q="""SELECT DISTINCT col1, col2 FROM df;"""
pysqldf = lambda q: sqldf(q, globals())
a_df = pysqldf(q)

비슷한 문제를 해결하기 위해, 저는 사용하고 있습니다.groupby:

print(f"Distinct entries: {len(df.groupby(['col1', 'col2']))}")

그것이 적절한지는 결과로 무엇을 하고 싶은지에 따라 달라질 것입니다. (나의 경우, 나는 단지 동등한 것을 원했습니다.)COUNT DISTINCT그림과 같이).

사용할 것 같습니다.drop duplicate데이터 프레임에 따라 유용하지 않을 수 있습니다.

다음을 찾았습니다.

[in] df['col_1'].unique()
[out] array(['A', 'B', 'C'], dtype=object)

그리고 날 위해 일했어요!

https://riptutorial.com/pandas/example/26077/select-distinct-rows-across-dataframe

거기에는 없다uniquedf에 대한 방법, 각 열의 고유 값 수가 같으면 다음과 같이 작동합니다.df.apply(pd.Series.unique)그렇지 않으면 오류가 발생합니다.또 다른 방법은 열 이름에 키를 지정하는 딕트에 값을 저장하는 것입니다.

In [111]:
df = pd.DataFrame({'a':[0,1,2,2,4], 'b':[1,1,1,2,2]})
d={}
for col in df:
    d[col] = df[col].unique()
d

Out[111]:
{'a': array([0, 1, 2, 4], dtype=int64), 'b': array([1, 2], dtype=int64)}

저는 다음이 가장 깨끗한 접근법이라고 생각합니다.

df.filter(items=['Column A', 'Column B']).drop_duplicates()

열 집합을 가져와서 더 큰 집합에서 더 작은 집합을 뺄 수 있습니다.

distinct_values = set(df['a'])-set(df['b'])

동일한 솔루션을 찾다가 우연히 Apache Spark for .NET(C#)을 사용하게 되었습니다.

다음은 도움이 되었습니다(폴더의 CSV 파일 목록이 주어짐).

string filePath = "file:///Users/me/dups/*";

var opts = new Dictionary<string, string>();
opts.Add("header", "true");
opts.Add("quote", "\"");
opts.Add("multiLine", "true");
opts.Add("sep", ",");

// load data
DataFrame df1 = spark.Read()
   .Options(opts)
   .Csv(filePath);

// columns to distinct on. in my case, there was 1 column I knew that was distinct per row so I listed all columns below minus that one.
Column[] columns = {
    Col("MyColumn1"),
    Col("MyColumn2"),
    // etc.
};

var distinctCount = df1
    .Select(columns)
    .Distinct()
    .Count();

Console.WriteLine(distinctCount);

언급URL : https://stackoverflow.com/questions/30530663/how-to-select-distinct-across-multiple-data-frame-columns-in-pandas

반응형